스프링 부트에서 @ControllerAdvice를 활용한 전역 예외처리
Global Exception Handling for Spring-Boot Application Using @ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandling {
protected Logger logger;
public GlobalExceptionHandling() {
logger = LoggerFactory.getLogger(getClass());
}
@ResponseBody
public ResponseEntity<?> handleUnauthenticationException(Exception e) {
return errorResponse(e, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({DataIntegrityViolationException.class, SQLIntegrityConstraintViolationException.class})
@ResponseBody
public ResponseEntity<?> handleConflictException(Exception e) {
return errorResponse(e, HttpStatus.CONFLICT);
}
@ExceptionHandler({ SQLException.class, DataAccessException.class, RuntimeException.class })
@ResponseBody
public ResponseEntity<?> handleSQLException(Exception e) {
return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler({ IOException.class, ParseException.class, ProcessingException.class, JsonParseException.class, JsonMappingException.class })
@ResponseBody
public ResponseEntity<?> handleParseException(Exception e) {
return errorResponse(e, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler({ InvalidKeyException.class, NoSuchAlgorithmException.class })
@ResponseBody
public ResponseEntity<?> handleHashException(Exception e) {
return errorResponse(new Exception("Encrypt/Decrypt key is requested"), HttpStatus.LOCKED);
}
@ExceptionHandler({ Exception.class })
@ResponseBody
public ResponseEntity<?> handleAnyException(Exception e) {
return errorResponse(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
protected ResponseEntity<ExceptionMessage> errorResponse(Throwable throwable,
HttpStatus status) {
if (null != throwable) {
return response(new ExceptionMessage(throwable), status);
} else {
return response(null, status);
}
}
protected <T> ResponseEntity<T> response(T body, HttpStatus status) {
return new ResponseEntity<T>(body, new HttpHeaders(), status);
}
}
출처: https://springboot.tistory.com/32?category=620230 [스프링부트는 사랑입니다]
'Spring Framework > Spring boot' 카테고리의 다른 글
자바 요일구하기 (0) | 2020.09.03 |
---|---|
스프링 비동기와 자바8의 CompletableFuture (0) | 2020.09.03 |
스프링에서 @Async로 비동기처리하기 @Async in Spring (0) | 2020.09.03 |
스프링부트 : REST 어플리케이션에서 예외처리하기 (0) | 2020.09.03 |
Spring MVC 예외처리 (0) | 2020.09.03 |
스프링부트와 OAuth2 - (4/4) (0) | 2020.09.03 |
스프링부트와 OAuth2 - (3/4) (0) | 2020.09.03 |
스프링부트와 OAuth2 - (2/4) (0) | 2020.09.03 |