SpringBoot 错误定制页面快速配置

SpringbBoot 错误页面定制详解

    • 引言
    • 方法一:继承BasicErrorController
    • 方法二:通过@ControllerAdvice 处理
    • 方法三:自定义html错误页面

引言

SpringBoot自动配置了错误页面,但可读性不是很高,而为了页面很友好,可读性更高,我们可以通过自己定制错误页面,得到一些自己想要的数据信息,具体请看下面操作

方法一:继承BasicErrorController

  1. 创建一个MyErrorController类继承BasicErrorController
/**
 1. 错误页面自定义
 */
public class MyErrorController extends BasicErrorController {

	/**
	* 创建构造方法并调用父类构造方法
	*/
    public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    /**
     *  重新爷爷类的getErrorAttributes的方法
     * @param request
     * @param includeStackTrace
     * @return
     */
    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        //调用爷爷类AbstractErrorController的getErrorAttributes方法
        //可以获取到错误参数
        Map<String, Object> map = super.getErrorAttributes(request, includeStackTrace);
        //可以对操作进行操作修改
        map.remove("timestamp");
        map.remove("status");
        map.remove("error");
        map.remove("path");
        map.put("code", "自定义参数"));
        //返回map集合
        return map;
    }
}
  1. 创建一个错误配置类,务必修改其他参数
/**
 1. 错误处理相关配置
 */
@Configuration
public class ErrorConfiguration {

	/**
	* 将MyErrorController注册到spring容器中
	*/
    @Bean
    public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties, ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
    	//创建一个MyErrorController对象并返回
        return new MyErrorController(errorAttributes, serverProperties.getError(), errorViewResolversProvider.getIfAvailable());
    }
}
  1. 结果调试
    SpringBoot 错误定制页面快速配置_第1张图片

方法二:通过@ControllerAdvice 处理

/**
 * 增强版Controller实现错误定制 所有Controller抛出异常后都将执行
 * 通过ResponseBody返回给页面
 */
@ControllerAdvice
public class ErrorControllerAdvice {

    //所有异常都捕捉 可自定义异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity handleException(Exception e){
        Map<String,Object> map = new HashMap();
        //逻辑处理
        map.put("message", "数据异常");
        map.put("type", "advice");
        //当前类抛出异常会回调给BasicErrorController
        //Assert.isNull(map,errorEnum.getCode());
        
        return new ResponseEntity(map, HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

SpringBoot 错误定制页面快速配置_第2张图片

方法三:自定义html错误页面

public class ResourceProperties {
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

可以在静态资源路径下创建error文件再创建错误页面,错误页面创建规则具体如下
SpringBoot 错误定制页面快速配置_第3张图片
(借鉴了其他博主的文章)
可以使用
4xx和5xx作为错误页面的文件名
来匹配这种类型的,所有错误
查找规则,精确优先
优先寻找,精确的状态码.html
如果,没有找到,就返回4xx.html页面
比如,寻找403错误页面
没有的话,返回4xx.html
SpringBoot 错误定制页面快速配置_第4张图片
结果调试
SpringBoot 错误定制页面快速配置_第5张图片

你可能感兴趣的:(Spring学习笔记)