springbootErrorPage

关于springBoot框架中全部异常页面的处理

首先我们看一组官网数据截图:

由于springBoot中自带相关错误信息的处理页面,如果我们不进行显现配置则会使用springBoot自带的错误展示页面。

其实springBoot的全局处理页面的配置很简单,如上图在相关地址添加上相应的页面就行。

下面我来们看下springBoot版本2.0x以上版本的全局异常页面的配置:

首先在配置文件中配置页面文件的默认存储位置及后缀名,然后创建相关的页面地址。

这里需要注意的是:异常页面的储存需要在error的文件下以及用协议号给jsp或其他页面模板命名。

然后配置异常页面处理类:

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
32
33
34
35
36
37
38


import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
*
* @description 全局异常处理类
*/
@Configuration
public class ErrorPageConfig {


@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
// //第一种:java7 常规写法
// return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
// @Override
// public void customize(ConfigurableWebServerFactory factory) {
// ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
// factory.addErrorPages(errorPage404);
// }
// };
//第二种写法:java8 lambda写法
return (factory -> {
ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "404");
ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "500");
factory.addErrorPages(errorPage404);
factory.addErrorPages(errorPage500);
});
}
}


这样全局异常处理页面的配置就全部完成。