예외 처리
이 글은 Spring의 기본 예외 처리 방식에서 시작해, 더 세밀한 예외 처리 방식으로 확장되는 흐름을 정리한다.
Spring 기본 예외 처리

Spring Boot는 예외가 발생하면 기본적으로 /error로 요청을 다시 전달하여 BasicErrorController가 처리한다.
동작 흐름은 다음과 같다.
- WAS가 컨트롤러 코드를 호출한다.
- 컨트롤러에서 예외가 발생한다.
- 처리되지 않은 예외가 WAS로 전달된다.
- Spring Boot가 등록한
/error컨트롤러가 호출된다. BasicErrorController가 기본 에러 응답을 반환한다.
기본 에러 응답에는 다음과 같은 값이 포함될 수 있다.
timestamp: 에러가 발생한 시간status: HTTP 상태 코드error: 에러 코드path: 에러가 발생한 URIexception: 최상위 예외 클래스 이름message: 에러 메시지errors:BindingException으로 발생한 에러 목록trace: 에러 스택 트레이스
{
"timestamp": "2021-12-31T03:35:44.675+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/product/5000"
}
DefaultErrorAttributes를 수정하면 기본 에러 응답 값을 조정할 수 있다.
하지만 상태 코드, 메시지, 응답 형식을 더 세밀하게 다루려면 별도의 예외 처리 전략이 필요하다.
Spring에서는 주로 다음 방식으로 예외를 처리한다.
@ResponseStatusResponseStatusException@ExceptionHandler@ControllerAdvice,@RestControllerAdvice
1. @ResponseStatus
@ResponseStatus는 예외가 발생했을 때 반환할 HTTP 상태 코드를 지정하는 어노테이션이다.
예외 클래스에 직접 붙여 사용할 수 있다.
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ProductNotFoundException extends RuntimeException {
}
예외와 HTTP 상태 코드가 고정되어 있을 때 사용하기 쉽다. 다만 예외 클래스에 상태 코드가 묶이기 때문에 상황에 따라 다른 상태 코드를 내려야 하는 경우에는 유연성이 떨어질 수 있다.
2. ResponseStatusException
ResponseStatusException은 코드에서 직접 HTTP 상태 코드와 메시지를 지정해 예외를 던질 수 있는 방식이다.
외부 라이브러리 예외처럼 직접 수정할 수 없는 예외를 HTTP 응답으로 변환할 때 사용할 수 있다.
@GetMapping("/products/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
try {
return ResponseEntity.ok(productService.getProduct(id));
} catch (ExternalApiException e) {
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "외부 API 호출에 실패했습니다.");
}
}
간단하게 상태 코드를 지정할 수 있지만, 예외 응답 Body를 일관된 형식으로 관리하기에는 부족하다.
3. @ExceptionHandler
@ExceptionHandler는 특정 예외를 처리할 메서드를 지정한다.
컨트롤러 내부에 작성하면 해당 컨트롤러에서 발생한 예외만 처리한다.
@RestController
@RequiredArgsConstructor
public class ProductController {
private final ProductService productService;
@GetMapping("/products/{id}")
public ProductResponse getProduct(@PathVariable Long id) {
return productService.getProduct(id);
}
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<String> handleProductNotFoundException(ProductNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(e.getMessage());
}
}
@ExceptionHandler를 사용하면 에러 응답 Body를 직접 만들 수 있다.
다만 여러 컨트롤러에서 같은 예외 처리가 필요하면 코드가 반복된다. 그래서 Spring은 전역적으로 예외를 처리할 수 있는 기능을 제공한다.
4. @ControllerAdvice, @RestControllerAdvice
@ControllerAdvice와 @RestControllerAdvice는 여러 컨트롤러에 전역 예외 처리를 적용할 때 사용한다.
@RestControllerAdvice: @ControllerAdvice + @ResponseBody (REST API에서 JSON 응답을 내려줄 때 사용)
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<ErrorResponse> handleProductNotFoundException(ProductNotFoundException e) {
ErrorResponse response = new ErrorResponse("NOT_FOUND", e.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(response);
}
}
전역 예외 처리를 사용하면 다음과 같은 장점이 있다.
- 하나의 클래스에서 여러 컨트롤러의 예외를 처리할 수 있다.
- 직접 정의한 에러 응답을 일관되게 내려줄 수 있다.
- 컨트롤러마다 반복되는
try-catch를 줄일 수 있다.
가능하면 하나의 ControllerAdvice에서 관리하고, 여러 개가 필요하다면 적용 범위와 순서를 명확히 지정하는 것이 좋다.
여러 ControllerAdvice를 사용한다면 Spring이 임의의 순서로 처리할 수 있기 때문에, 일관된 예외 응답을 위해서 @Order, basePackages, annotations 적용 범위를 명확히 지정해야 한다.
REST API에서 주로 사용하는 방식
REST API에서는 보통 @RestControllerAdvice와 @ExceptionHandler를 함께 사용한다.
서비스에서 예외 발생
→ @RestControllerAdvice에서 예외 감지
→ @ExceptionHandler로 예외별 처리
→ 공통 ErrorResponse 반환
public record ErrorResponse(
String code,
String message
) {
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ProductNotFoundException.class)
public ResponseEntity<ErrorResponse> handleProductNotFoundException(ProductNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse("NOT_FOUND", e.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ErrorResponse("INTERNAL_SERVER_ERROR", "서버 오류가 발생했습니다."));
}
}