💦 서비스에서 발생할수 있는 특정 예외들을 모아서 한번에 같은 형식으로 처리하는 클래스를 만들자.
💦 이때 ErrorDetails 클래스에 시간, 메세지, 디테일을 넣어 만들자.
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
}
@ExceptionHandler
@ControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler{
//ResourceNotFoundException : 리소스를 찾지 못한경우 (post, comment 등)
//BlogAPIException : 해당 포스트의 댓글이 아닐경우
}
//ResourceNotFoundException : 리소스를 찾지 못한경우 (post, comment 등) (404 Not found)
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException e,
WebRequest webRequest){
ErrorDetails errorDetails = new ErrorDetails(new Date(), e.getMessage(), webRequest.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
//모든 예외 처리
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDetails> handleGlobalException(Exception e, WebRequest webRequest){
ErrorDetails errorDetails = new ErrorDetails(new Date(), e.getMessage(), webRequest.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
참고
https://jaehun2841.github.io/2018/08/30/2018-08-25-spring-mvc-handle-exception/#test-case