์ ํ๋ฆฌ์ผ์ด์
๋ด์์ ๋ฐ์ํ๋ ์์ธ๋ฅผ ์ฒ๋ฆฌํ๋ ๋ฉ์ปค๋์ฆ์ ์ ๊ณตํ๋ ๊ธฐ๋ฅ์
๋๋ค.
์ฃผ๋ก @Controller ๋๋ @RestController ํด๋์ค ๋ด๋ถ์์ ์ ์๋๋ฉฐ,
ํน์ ์์ธ๊ฐ ๋ฐ์ํ์ ๋ ํด๋น ์์ธ๋ฅผ ์ฒ๋ฆฌํ๋ ๋ฉ์๋๋ฅผ ์ง์ ํ ์ ์์ต๋๋ค.
@ExceptionHandler,@ControllerAdvice ์ ๋
ธํ
์ด์
์ ์ฌ์ฉํ๋ค.
2.Exception Handler ์ฌ์ฉ์์
RuntimeException์ด ๋ฐ์ํ๋ฉด, handleRuntimeException ๋ฉ์๋๊ฐ ํด๋น
์์ธ๋ฅผ ์ฒ๋ฆฌํ๊ฒ ํ๋ค.
@ RestController
@ RequestMapping ("/api" )
public class MyController {
@ GetMapping ("/example" )
public String example () {
if (true ) {
throw new RuntimeException ("This is a runtime exception" );
}
return "example" ;
}
@ ExceptionHandler (RuntimeException .class )
public ResponseEntity <String > handleRuntimeException (RuntimeException ex ) {
return new ResponseEntity <>("Exception handled: " + ex .getMessage (), HttpStatus .INTERNAL_SERVER_ERROR );
}
}
2-2.@ControllerAdvice(๊ธ๋ก๋ฒ ์์ธ ์ฒ๋ฆฌ)
@ControllerAdvice๋ ์ ํ๋ฆฌ์ผ์ด์
์ ์ญ์์ ๋ฐ์ํ๋ ์์ธ๋ฅผ ์ฒ๋ฆฌํ ์ ์๊ฒ
ํด์ค๋๋ค.
GlobalExceptionHandler ํด๋์ค๊ฐ ์ ํ๋ฆฌ์ผ์ด์
์ ์ญ์์ ๋ฐ์ํ๋
RuntimeException ๋ฐ Exception์ ์ฒ๋ฆฌํฉ๋๋ค.
import org .springframework .http .HttpStatus ;
import org .springframework .http .ResponseEntity ;
import org .springframework .web .bind .annotation .ControllerAdvice ;
import org .springframework .web .bind .annotation .ExceptionHandler ;
@ ControllerAdvice
public class GlobalExceptionHandler {
@ ExceptionHandler (RuntimeException .class )
public ResponseEntity <String > handleRuntimeException (RuntimeException ex ) {
return new ResponseEntity <>("Global Exception handled: " + ex .getMessage (), HttpStatus .INTERNAL_SERVER_ERROR );
}
@ ExceptionHandler (Exception .class )
public ResponseEntity <String > handleException (Exception ex ) {
return new ResponseEntity <>("Global Exception handled: " + ex .getMessage (), HttpStatus .BAD_REQUEST );
}
}