티스토리 뷰

Spring

[Spring] 예외 처리 우선 순위

snail voyager 2025. 5. 1. 23:59
728x90
반응형

 

기본적인 예외 처리 흐름

Spring MVC에서 컨트롤러 또는 서비스 계층에서 예외가 발생하면, DispatcherServlet이 이를 감지하고 적절한 방식으로 처리합니다.

  1. 컨트롤러 또는 서비스에서 예외 발생
  2. HandlerExceptionResolver가 예외를 처리할 수 있는지 확인
  3. 등록된 예외 처리 로직(@ExceptionHandler, @ControllerAdvice 등) 실행
  4. 예외가 처리되지 않으면 기본적인 Spring 예외 처리(DefaultHandlerExceptionResolver) 실행
  5. 그래도 해결되지 않으면, sendError()를 호출하여 기본적인 HTTP 에러 응답 반환

예외 처리 우선순위

Spring MVC에서 예외가 발생하면 아래 순서로 처리됩니다.

  1. @ExceptionHandler (컨트롤러 단위 예외 처리)
  2. @ControllerAdvice (전역 예외 처리)
  3. HandlerExceptionResolver (커스텀 예외 처리기)
  4. DefaultHandlerExceptionResolver (Spring 기본 예외 처리기)
  5. BasicErrorController (Spring Boot 기본 에러 처리기)
  6. 서버 기본 예외 처리 (sendError())

@ExceptionHandler (개별 컨트롤러 예외 처리)

@RestController
@RequestMapping("/api")
public class SampleController {

    @GetMapping("/test")
    public String test() {
        if (true) {
            throw new IllegalArgumentException("잘못된 요청입니다.");
        }
        return "OK";
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
        return ResponseEntity.badRequest().body(ex.getMessage());
    }
}

 

@ControllerAdvice (전역 예외 처리)

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
        return ResponseEntity.badRequest().body("잘못된 요청: " + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneralException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("서버 오류 발생: " + ex.getMessage());
    }
}

HandlerExceptionResolver (커스텀 예외 처리기)

@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        try {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "커스텀 예외 처리: " + ex.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView();
    }
}

DefaultHandlerExceptionResolver (기본 제공 예외 처리기)

예외 클래스  기본 HTTP 상태 코드
HttpRequestMethodNotSupportedException 405 Method Not Allowed
HttpMediaTypeNotSupportedException 415 Unsupported Media Type
MissingPathVariableException 500 Internal Server Error
MissingServletRequestParameterException 400 Bad Request
TypeMismatchException 400 Bad Request
HttpMessageNotReadableException 400 Bad Request

BasicErrorController (Spring Boot의 기본 에러 컨트롤러)

 

  • 예외가 발생하면 /error 엔드포인트를 통해 JSON 응답을 반환함
  • 에러 메시지를 커스터마이징하려면 ErrorController 인터페이스를 구현해야 함
@RestController
@RequestMapping("/error")
public class CustomErrorController implements ErrorController {

    @GetMapping
    public ResponseEntity<String> handleError() {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("커스텀 에러 메시지");
    }
}

 

 

728x90
반응형
반응형
300x250