Spring 예외처리 방법
- Controller 코드 수정
- @ExceptionHandler 사용
-> Spring에서 제공하는 ResponseEntity 클래스를 사용
💡 ResponseEntity는 HTTP response object 를 위한 Wrapper,
아래와 같은 것들을 담아서 response로 내려주면 아주 간편하게 처리가 가능합니다.
- HTTP status code
- HTTP headers
- HTTP body
@PostMapping("/folders")
public ResponseEntity<RestApiException> addFolders(@RequestBody FolderRequestDto folderRequestDto,
@AuthenticationPrincipal UserDetailsImpl userDetails) {
try {
List<String> folderNames = folderRequestDto.getFolderNames();
folderService.addFolders(folderNames, userDetails.getUser());
return new ResponseEntity<>(HttpStatus.OK);
} catch(IllegalArgumentException ex) {
RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.BAD_REQUEST);
}
}
-> addFolders 메서드를 보시면 이제 try-catch문을 통해서
return new ResponseEntity<>(HttpStatus.OK);
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.BAD_REQUEST);
이렇게 나뒤어서 응답을 내주는 것 을 볼 수 있다.
에러문구도 캐치하고, 그에 따라서 어느 부문에서 오류가 났는지 적어서 보내 줄 수 있다.
-> 모든 Controller에 예외처리 적용하는 방법
: @ExceptionHandler
@ExceptionHandler
Spring에서 예외처리를 위한 애너테이션
AOP를 이용한 예외처리 방식(깔끔한 코드가능)
@ExceptionHandler({IllegalArgumentException.class})
public ResponseEntity<RestApiException> handleException(IllegalArgumentException ex) {
RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.BAD_REQUEST
);
}