Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

ENN

Spring 예외 처리 : HandlerExceptionResolver 본문

백엔드

Spring 예외 처리 : HandlerExceptionResolver

ParkIsComing 2022. 9. 2. 01:38

HandlerExceptionResolver의 개념

HandlerExceptionResolver는 Controller의 작업 중 발생한 예외를 처리하는 객체이다. 예외가 발생하면 DispatcherServlet이 먼저 전달 받고, 다시 Servlet 밖의 Servlet Container가 처리하는데 이때 HandlerExceptionResolver의 등록 여부에 따라 이후 흐름이 아래처럼 달라진다.

  • HandlerExceptionResolver 등록 X -> HTTP Status 500
  • HandlerExceptionResolver 등록 O -> DispatcherServlet에서 HandlerExceptionResolver가 에러 처리가 가능한지 확인하고, 가능하면 HandlerExceptionResolver에 에러 처리를 위임

HandlerExceptionResolver의 사용

HandlerExceptionResolver는 interface인 HandlerExceptionResolver를 implements하여 구현할 수 있다. ExceptionResolver 메서드는 ModelAndView를 반환하도록 작성한다. 이는 예외가 발생한 경우 ModelAndView를 리턴하여 정상 흐름처럼 변경하기 위함이다. null을 반환하도록 할 수도 있는데 이는 예외를 해당 ExceptionResolver에서 처리하지 못한 경우 예외를 서블릿 밖으로 보내기 위함이다.

 

public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
    public ModelAndView resolveException(HttpServletRequest request,
    HttpServletResponse response, Object handler, Exception ex) {
        try {
            if (ex instanceof IllegalArgumentException) {
                log.info("IllegalArgumentException resolver to 400");
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,ex.getMessage());
                return new ModelAndView();
            }
        } catch (IOException e) {
            log.error("resolver ex", e);
        }
    return null;
}

 

ExceptionResolver의 등록

ExceptionResolver는 아래처럼 등록해야 사용 가능하다.

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new MyHandlerException());//ExceptionResolver 등록
    }
}