스프링 부트가 기본으로 제공하는 ExceptionResolver
예외가 발생하면 ExceptionHandlerExceptionResolver가 작동해 해당 에러를 처리할 수 있는 @ExceptionHandler를 찾는다.
컨테이너까지 예외가 전달되지 않고 @ExceptionHandler에서 예외를 잡는다. 따라서 스프링 MVC에서 예외 처리는 끝이난다.
결과적으로 WAS 입장에서는 정상 처리가 된 것이다.(상태코드 200, 변경하면 됨)
@ExceptionHandler를 사용하면 컨테이너까지 예외가 올라가서 재요청을 해 추가 프로세스가 실행되는 과정 없이 예외처리가 깔끔해진다.
//@RestControllerAdvice(basePackages = "org.example.controllers")
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ErrorResult exHandler(Exception e){
log.error("[exceptionHandler] ex", e);
return new ErrorResult("EX", "내부 오류");
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public ErrorResult illegalExHandler(IllegalArgumentException e){
log.error("[exceptionHandler] ex", e);
return new ErrorResult("BAD", e.getMessage());
}
@ExceptionHandler
public ResponseEntity<ErrorResult> userExHandler(UserException e){
log.error("[exceptionHandler] ex", e);
return new ResponseEntity<>(new ErrorResult("USER-EX", e.getMessage()), HttpStatus.BAD_REQUEST);
}
html 뷰로 오류를 보여줄때는 스프링에서 제공하는 BasicErrorController 를 사용하는게 편하다.
BasicErrorController는 기본적인 로직을 모두 구현해두었다.
개발자는 오류 페이지만 등록하면 된다.
resources/templates/error/500.html
resources/templates/error/404.html
resources/templates/error/5xx.html
resources/static/error/4xx.html
resources/templates/error.html(적용 대상이 없을 때)
해당 경로 위치에 HTTP 상태 코드 이름의 뷰 파일을 넣어두면 된다.
뷰 템플릿이 정적 리소스보다 우선순위가 높고, 404, 500처럼 구체적인 것이 5xx처럼 덜 구체적인 것 보다
우선순위가 높다.
5xx, 4xx 라고 하면 500대, 400대 오류를 처리해준다.