介绍
如果不处理404、500错误页,是英文提示,不够友好,如下:
在前后台分离式开发时,要返回给前端json格式的数据,此时返回一个html代码,会让前端崩溃
所以,我们要指定404、500这类的错误页面
方式一:默认方式添加错误页
按照下图的目录结构:src/main/resources/static/error,创建404.html、500.html页面,当报错时会显示相应的错误页面
优缺点
这种方式简单,当报错时,转发到相应的html页面
但在前后台分离式开发时,报错后,会返回html代码,所以不适合前后台分离式开发
方式二:通过配置类实现指定错误页
创建配置类
package top.malaoshi.stdsecurity.config;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
/*报404错误时,转发到/404.html页面*/
ErrorPage e404 = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
/*报500错误时,转发到/500.html网页*/
ErrorPage e500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");
registry.addErrorPages(e404, e500);
}
}
- 报404错误时,转发 到
/404.html页面 - 报500错误时,转发 到
/500.html网页
创建错误页
根据上面转发的错误页面可知,页面所在路径是:src/main/resources/static/
下图是目录结构:
优缺点
- 相对比较复杂,需要通过配置类实现
- 可以指定错误页,也可以指定返回json


