Spring Boot Web Error Page处理

spring Boot默认是whitelabel error page. 其实我们可以自己处理,由于时间有限,所以就简单说明一下方法。

首先配置

@Configuration
public class ErrorPageConfig  {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            public void customize(ConfigurableEmbeddedServletContainer container) {
                ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/400.html");
                ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404/");
                ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");

                container.addErrorPages(error400Page, error401Page, error404Page, error500Page);
            }
        };
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

细心的朋友会看到,404不是html, 这儿为了掩饰,所以用了两种方法,如果是html的方法,需要将html文件放到resources/static目录下。404处理方式,就需要我们自己处理/404请求,与一般的Controller中处理Request类似。如下:

@RequestMapping("404")
    public String error404() {
        return "error404";
    }
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

用到了模版,所以需要在resources/templates目录下创建error404.html文件 
其实配置的时候,也可以用继承的方式:

@Configuration
public class ErrorPageConfig implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.addErrorPages(
                new ErrorPage(HttpStatus.BAD_REQUEST, "/4O0.html"),
                new ErrorPage(HttpStatus.UNAUTHORIZED, "/4O1.html"),
                new ErrorPage(HttpStatus.NOT_FOUND, "/404/"),
                new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html")
        );
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

关于异常的处理可以参看:http://blog.didispace.com/springbootexception/

posted @ 2017-08-14 17:58  牧之丨  阅读(887)  评论(0编辑  收藏  举报