예외처리를 따로 배우는 이유
웹 애플리케이션의 에러

Response 메시지
start-line (상태줄) : API 요청 결과 (상태 코드, 상태 텍스트)
HTTP/1.1 404 Not Found
Spring 예외처리 방법
@ExceptionHandler@ExceptionHandler 는 Spring에서 예외처리를 위한 애너테이션 @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
);
}


Global 예외 처리

@ControllerAdvice 사용
@ControllerAdvice@ControllerAdvice는 Spring에서 예외처리를 위한 클래스 레벨 애너테이션@ControllerAdvice 가 붙은 클래스에서는 @ExceptionHandler메서드를 정의하여 예외를 처리하는 로직을 담을 수 있다.@ControllerAdvice 를 사용하는 이유?@ControllerAdvice를 사용하면 예외 처리 로직을 모듈화하여 관리하기 쉽기 때문에, 팀 내에서 공통된 예외 처리 로직을 공유하거나 다른 팀에서 예외 처리를 참고할 수 있다. 이를 통해 개발 생산성을 향상시키는 것도 가능.@RestControllerAdvice
@RestControllerAdvice 적용
@RestControllerAdvice
public class GlobalExceptionHandler {
@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
);
}
}