Framework & Library/Spring Boot
[Spring Boot] : @ExceptionHandler 사용해 보기(2)
오주현
2022. 3. 10. 15:29
반응형
@ExceptionHandler 사용해 보기(2)
@Data
@AllArgsConstructor
public class ErrorResult {
private String code;
private String message;
}
예외가 발생했을 때 API 응답으로 사용하는 객체를 정의한다.
@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);
ErrorResult errorResult = new ErrorResult("USER-EX", e.getMessage());
return new ResponseEntity(errorResult, HttpStatus.BAD_REQUEST);
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler
public ErrorResult exHandler (Exception e) {
log.error("[exceptionHandler] ex", e);
return new ErrorResult("EX", "내부 오류");
}
ExceptionHandler 어노테이션을 사용하고 컨트롤러에서 처리하고 싶은 예외를 지정해주어 해당 예외 발생 시 이 메서드가 호출되도록 한다. 지정한 예외 말고도 자식 클래스까지 다 잡을 수 있다.
ExceptionHandler에 다양한 파라미터와 응답을 지정할 수 있다.
우선순위는 디테일한 것이 우선된다.
스프링 MVC 2편 - 백엔드 웹 개발 활용 기술을 참고하여 공부하였습니다.
반응형