본문 바로가기

Web/spring

[Spring framework Web MVC docs] 1.1.8. Exceptions

728x90

틀린 해석이 있다면 알려주세요

 

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-exceptionhandlers

 

Web on Servlet Stack

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. The formal name, "Spring Web MVC," comes from the name of its source module (spring-webmvc), but it is more commonl

docs.spring.io


 

 

1.1.8. Exceptions

 

요청 매핑 중의 예외 발생이나 요청 핸들러에서 예외가 발생할 경우, DispatcherServlet 에서 예외를 해결하고 대체처리를 제공하기 위해

HandlerExceptionResolber 로 위임한다

 

 HandlerExceptionResolver 

SimpleMappingExceptionResolver A mapping between exception class names and error view names. Useful for rendering error pages in a browser application.
DefaultHandlerExceptionResolver Resolves exceptions raised by Spring MVC and maps them to HTTP status codes. See also alternative ResponseEntityExceptionHandler and Error Responses.
ResponseStatusExceptionResolver Resolves exceptions with the @ResponseStatus annotation and maps them to HTTP status codes based on the value in the annotation.
ExceptionHandlerExceptionResolver Resolves exceptions by invoking an @ExceptionHandler method in a @Controller or a @ControllerAdvice class. See @ExceptionHandler methods.
 

 

 

 

Chain of Resolvers

 

HandlerExceptionResolver 을 선언하고,

필요에 따라 order properties 를 설정하여 세팅하면

Order 속성이 높을 수록 나중에 배치가 된다

 

HandlerExceptionResolver 가 반환하는 것들

  • a ModelAndView that points to an error view.
  • An empty ModelAndView if the exception was handled within the resolver.
  • null if the exception remains unresolved, for subsequent resolvers to try, and, if the exception remains at the end, it is allowed to bubble up to the Servlet container.

The MVC Config automatically declares built-in resolvers for default Spring MVC exceptions, for @ResponseStatus annotated exceptions, and for support of @ExceptionHandler methods. You can customize that list or replace it.

 

 

Container Error Page

 

예외가 해결되지 않은 상태로 HandlerExceptionResolver 에 남아있거나, 오류 상태를 설정해뒀을 경우 서블릿 컨테이너에서 기본 오류 페이지를 렌더링할 수 있다

 

 

@RestController
public class ErrorController {

    @RequestMapping(path = "/error")
    public Map<String, Object> handle(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", request.getAttribute("jakarta.servlet.error.status_code"));
        map.put("reason", request.getAttribute("jakarta.servlet.error.message"));
        return map;
    }
}
728x90