ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Spring-Error] 예외 페이지
    legacy/Spring 2023. 6. 26. 15:23

     

    내가 겪은 문제

    WAS로 예외 또는 sendError가 전송되었을 때, 해당 에러를 처리할 예외 페이지를 등록했음에도 서블릿의 기본 예외 페이지가 보였다.

    예외 페이지 등록 

    public class WebServerCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
        @Override
        public void customize(ConfigurableWebServerFactory factory) {
            ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error-page/400");
            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error-page/404");
            ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error-page/500");
            ErrorPage exErrorPage = new ErrorPage(RuntimeException.class, "/error-page/500");
            
            factory.addErrorPages(errorPage400, errorPage404, errorPage500, exErrorPage);
        }
    }

    예외를 처리하는 컨트롤러

    @Controller
    public class ServletException {
        @GetMapping("/error-404")
        public void error404(HttpServletResponse response) throws IOException {
            response.sendError(404, "404 오류!");
        }
        @GetMapping("/error-500")
        public void error500(HttpServletResponse response) throws IOException {
            response.sendError(500);
        }
        
        @GetMapping("/error-page/404")
        public String errorPage404(HttpServletRequest request, HttpServletResponse response) {
            return "/error-page/404";
        }
    
        @GetMapping("/error-page/500")
        public String errorPage500(HttpServletRequest request, HttpServletResponse response) {
            return "/error-page/500";
        }
    }

     


     

    해결

    예외 페이지 등록하는 클래스에 @Component 애너테이션을 붙이지 않았다. 그렇기 때문에 컨트롤러에서 컴포넌트 스캔 대상이 되지 않기 때문에 페이지를 찾지 못하는 것이었다.

    @Component // 컴포넌트 애너테이션 추가
    public class WebServerCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
        @Override
        public void customize(ConfigurableWebServerFactory factory) {
            ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error-page/400");
            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error-page/404");
            ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error-page/500");
            ErrorPage exErrorPage = new ErrorPage(RuntimeException.class, "/error-page/500");
            
            factory.addErrorPages(errorPage400, errorPage404, errorPage500, exErrorPage);
        }
    }

Designed by Tistory.