springboot错误处理机制

在这里插入图片描述

1.一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则),决定去哪个请求路径。默认/error
	ServerProperties-->ErrorProperties-->(@Value("${error.path:/error}")) 从文件中获取error.path路径,如果没有就使用/error请求路径
					     private String path = "/error";

2.接下来由BasicErrorController处理器来处理这个请求,根据请求头决定去哪个页面或者返回json数据
	@RequestMapping("${server.error.path:${error.path:/error}}") 处理哪个请求,如果在配置文件中没有配置错误请求,则默认处理/error请求
	public class BasicErrorController extends AbstractErrorController
	里面调用了DefaultErrorViewResolver视图解析器解析视图

3.去哪个页面由DefaultErrorViewResolver解析得到
	String errorViewName = "error/" + viewName;viewName为错误状态码,例如error/404
	如果有模板引擎可以解析这个页面地址就用模板引擎解析,没有的话就去静态资源路径下找error/404.html页面
	
4.错误页面的信息DefaultErrorAttributes
	timestamp:时间戳,status:状态码,error:错误提示,exception:异常对象
	,message:异常消息,errors:JSR303数据校验的错误都在这里
	
可以定制页面,在页面中定制错误的信息数据
如何定制错误的json数据;

​ 自定义异常处理&返回定制json数据;

@ControllerAdvice
public class MyExceptionHandler {

    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map<String,Object> handleException(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        return map;
    }
}
//没有自适应效果...
转发到/error进行自适应响应效果处理
 @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码  4xx 5xx,否则就不会进入定制错误页面的解析流程
        /**
         * Integer statusCode = (Integer) request
         .getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        //转发到/error
        return "forward:/error";
    }
将我们的定制数据携带出去;

出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);

​ 1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;

​ 2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;

​ 容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;

自定义ErrorAttributes

//给容器中加入我们自己定义的ErrorAttributes
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
        map.put("company","error info");
        return map;
    }
}

最终的效果:响应是自适应的,可以通过定制ErrorAttributes改变需要返回的内容,

在这里插入图片描述
错误页面:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值