
API 예외처리
HTTP 상태 코드 종류
-2xx Success → 200번대의 상태코드는 성공을 의미!
-4xx Client Error → 400번대의 상태코드는 클라이언트 에러, 즉 잘못된 요청을 의미!
-5xx Server Error → 500번대의 상태코드는 서버 에러, 즉 정확한 요청에 서버쪽 사유로 에러가 난 상황을 의미!
-> Spring에서는 아래와 같은 아주 편리한 enum도 제공하고 있다. HttpStatus
Spring 예외처리 방법
@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);
}
}
return new ResponseEntity<>(HttpStatus.OK);
return new ResponseEntity<>(
// HTTP body
restApiException,
// HTTP status code
HttpStatus.BAD_REQUEST);
-> 에러문구 캐치하고, 그에 따라서 어느 부문에서 오류가 났는지 적어서 보내 줄 수 있다.
@ExceptionHandler@ExceptionHandler 는 Spring에서 예외처리를 위한 애너테이션이다.@ ExceptionHandler 가 붙어있는 메서드는 Controller에서 예외가 발생했을 때 호출 되며, 해당 예외를 처리하는 로직을 담고 있다.@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
);
}