SpringMVC 기반 애플리케이션에서 예외를 처리하는 방법이 무엇인지, 어떻게 클라이언트에 적절한 메세지를 보내는지 등에 대해 알아본다.
try - catch
문 활용해 예외 처리 혹은 상위 메소드로 넘김@ExceptionHandler
사용시 Controller에서 발생하는 예외 처리 가능@Controller
public class ExceptionHandlingController {
// @RequestHandler methods
...
// Exception handling methods
// 사전에 정의된 예외를 HTTP 상태 코드로 변환
@ResponseStatus(value=HttpStatus.CONFLICT,
reason="Data integrity violation") // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void conflict() {
// Nothing to do
}
// 오류 표시에 사용할 이름 지정
@ExceptionHandler({SQLException.class,DataAccessException.class})
public String databaseError() {
// Nothing to do.
// view resolver에 전달되는 오류 페이지의 logical name 반환.
// Note that the exception is NOT available to this view (it is not added
// to the model) but see "Extending ExceptionHandlerExceptionResolver"
// below.
return "databaseError";
}
// Total control - setup a model and return the view name yourself. Or
// consider subclassing ExceptionHandlerExceptionResolver (see below).
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
}
@ControllerAdvice
와 달리 응답을 Json으로 내려준다.@RestControllerAdvice
public class GlobalExceptionAdvice{
}
@RestControllerAdvice
public class GlobalExceptionAdvice{
@ExceptionHandler
public ResponseEntity hadleMethodNotValid(MethodArgumentNotValidException e){
final List<FieldError>fieldErros = e.getBibndingResult().getFieldErrors();
...
}
@ExceptionHandler
public ResponseEntity handleConstraintViolationException(ConstraintViolationException e){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}