【问题标题】:Spring boot redirect to error page when catch the thymeleaf exception捕获 thymeleaf 异常时 Spring Boot 重定向到错误页面
【发布时间】:2020-11-10 20:15:52
【问题描述】:

当发生 Thymeleaf 错误(即片段不存在)时,我想重定向到我的自定义错误页面 (/error/page)。

我的问题是,如果有任何错误,整个错误页面都会被渲染到 Thymeleaf 片段中。

我已尝试编写自定义错误处理程序和自定义错误控制器,它适用于任何其他异常(重定向到我的自定义错误页面),但在发生 Thymeleaf 错误时则不行。

    @Controller
    public class CustomErrorController implements ErrorController {
    
        private final String ERROR_PATH = "/error";
    
        @RequestMapping(ERROR_PATH)
        public String handleError(HttpServletRequest request) {
            Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
    
            if (status != null) {
                int statusCode = Integer.parseInt(status.toString());
    
                if (statusCode == HttpStatus.NOT_FOUND.value()) {
                    return "redirect:/error/page";
                } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                    return "redirect:/error/page";
                }
            }
            // Thymeleaf error -> status code 200 and doesn't work redirect
            return "redirect:/error/page";
        }
    
        @Override
        public String getErrorPath() {
            return ERROR_PATH;
        }
    
        @ModelAttribute(name = "url")
        public String getUrl(@AuthenticationPrincipal User user) {
            return user != null
                    ? "rooms"
                    : "";
        }
    }
    @Controller
    public class DefaultErrorController {
    
        @RequestMapping("/error/page")
        public String handleError() {
            return "errors/error";
        }
    
        @ModelAttribute(name = "url")
        public String getUrl(@AuthenticationPrincipal User user) {
            return user != null
                    ? "rooms"
                    : "";
        }
    
    }

    public class ThymeleafErrorFilter implements Filter {
    
        @Override
        public void init(final FilterConfig filterConfig) {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            try {
                filterChain.doFilter(servletRequest, servletResponse);
            } catch (final NestedServletException nse) {
                if(nse.getCause() instanceof TemplateEngineException) {
                    // redirec to error page
                }
                throw nse;
            }
        }
    
        @Override
        public void destroy() {
        }
    }

Application.properties:

    ############## ERROR PAGE ################
    server.error.whitelabel.enabled=false
    server.error.path=/error

@EnableAutoConfiguration AppConfig.java

    @Bean
    public FilterRegistrationBean<ThymeleafErrorFilter> thymeleafErrorFilter() {
        var thymeleafErrorFilter = new FilterRegistrationBean<ThymeleafErrorFilter>();
        thymeleafErrorFilter.setName("thymeleafErrorFilter");
        thymeleafErrorFilter.setFilter(new ThymeleafErrorFilter());
        thymeleafErrorFilter.addUrlPatterns("/*");
        return thymeleafErrorFilter;
    }

如果百里香叶片段不存在。 我们在 ThymeleafErrorFilter 中检测到它。在spring调用/error(我们在CustomErrorController中捕获)之后,在CustomErrorController中,状态码是200,redirect不起作用。

【问题讨论】:

    标签: java spring spring-boot exception thymeleaf


    【解决方案1】:

    您应该使用@ControllerAdvise 来处理您的异常并提供一个视图来呈现错误。

    看这个:

    
    @ControllerAdvice
    @Slf4j
    public class ErrorControllerAdvice {
     
    
        @ExceptionHandler(StorageException.class)  //handle this exception
        @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
        public String storageException(final StorageException throwable, final Model model) {
            log.error("Exception during execution of application", throwable);
            model.addAttribute("errorMessage", "Failed to store file"); //custom message to render in HTML
            return "error";  //the html page in resources/templates folder
        }
    
    
    /// handle other exeptions
    

    观点:

    error.html

    <h1> Opps.. Sorry about this. </h1>
    <p th:utext="${errorMessage}"></p>
    
    

    更多详情请见https://github.com/gtiwari333/spring-boot-blog-app/blob/master/src/main/java/gt/app/web/mvc/ErrorControllerAdvice.java。

    【讨论】:

    • @ControllerAdvice 注解不起作用,因为您只能将其用于控制​​器内部的异常,而这里您要在视图中处理异常。
    • you can only use it for exception inside a controller 这是什么意思?澄清一下,@ControllerAdvice 处理控制器方法抛出的异常
    • 另外,here you want to process exception in a view. NO.我没有处理视图中的异常。我只是在视图中显示消息。
    • 如果我得到 thymeleaf 异常,那么 @ExceptionHandling 不会捕捉到它。因此,当应用程序到达控制器时,@ExcaptionHandling 可以捕获它们。并且重定向到错误页面很重要,因为如果我不重定向到错误页面,那么 thymeleaf 将使用错误页面部分呈现整个页面。
    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 2013-04-11
    • 2021-12-21
    • 1970-01-01
    • 2019-09-05
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多