티스토리 뷰

Spring

Spring Error Handling

토마토계란 2021. 12. 22. 01:39

  • Spring 3.2 이전
    • @ExceptionHandler
      • 컨트롤러 수준에서 작동
      • 각 컨트롤러에 명시해주어야 함
    • HandlerExceptionResolver
      1. ExceptionHandlerExceptionResolver
        • DespatcherServlet 안에서 기본적으로 실행된다
        • @ExceptionHandler 메커니즘이 동작하게 해주는 주요 컴포넌트
      2. DefaultHandlerExceptionResolver
      3. ResponseStatusExceptionResolver
        • DespatcherServlet 안에서 기본적으로 실행된다
        • custom exception에 @ResponseStatus로 상태 코드를 매핑하면 해당 상태 코드로 세팅해준다
        • body는 여전히 null
      4. Custom HandlerExceptionResolver
        • DefaultHandlerExceptionResolver와 ResponseStatusExceptionResolver combination
        @Component
        public class RestResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver {
        
            @Override
            protected ModelAndView doResolveException(
              HttpServletRequest request, 
              HttpServletResponse response, 
              Object handler, 
              Exception ex) {
                try {
                    if (ex instanceof IllegalArgumentException) {
                        return handleIllegalArgument(
                          (IllegalArgumentException) ex, response, handler);
                    }
                    ...
                } catch (Exception handlerException) {
                    logger.warn("Handling of [" + ex.getClass().getName() + "] 
                      resulted in Exception", handlerException);
                }
                return null;
            }
        
            private ModelAndView 
              handleIllegalArgument(IllegalArgumentException ex, HttpServletResponse response) 
              throws IOException {
                response.sendError(HttpServletResponse.SC_CONFLICT);
                String accept = request.getHeader(HttpHeaders.ACCEPT);
                ...
                return new ModelAndView();
            }
        }
        
  • Spring 3.2
    • @ControllerAdvice (RestControllerAdvice)
      • ExceptionHandler 와 달리 하나의 컨트롤러가 아닌 전체 컨트롤러에 적용되는 exception handler이다.
  • Spring 5
    • ResponseStatusException
    에러 메시지가 잘 정의되어있어야 하는게 전제 조건이다.

'Spring' 카테고리의 다른 글

Controller의 response 는 model 과 다른 필드를 가지거나 숨겨야 하는 경우가 있는데 어떻게 설계?  (0) 2021.12.22
WebClient 와 WebFlux  (0) 2021.12.22
Cacheable annotation  (0) 2021.12.22
AOP  (0) 2021.12.22
Spring Security  (0) 2021.12.22
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/12   »
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
글 보관함