Springboot2.0自适应效果错误响应过程解析
这篇文章主要介绍了Springboot2.0自适应效果错误响应过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
实现效果当访问thymeleaf渲染页面时,显示的是自定义的错误页面
当以接口方式访问时,显示的是自定义的json数据响应
1.编写自定义异常
packagecn.jfjb.crud.exception;
/**
*@authorjohn
*@date2019/11/24-9:48
*/
publicclassUserNotExistExceptionextendsRuntimeException{
publicUserNotExistException(){
super("用户不存在");
}
}
2.自定义异常处理&返回定制json数据,转发到/error进行自适应响应效果处理
packagecn.jfjb.crud.handler;
importcn.jfjb.crud.exception.UserNotExistException;
importorg.springframework.web.bind.annotation.ControllerAdvice;
importorg.springframework.web.bind.annotation.ExceptionHandler;
importjavax.servlet.http.HttpServletRequest;
importjava.util.HashMap;
importjava.util.Map;
/**
*@authorjohn
*@date2019/11/24-10:43
*/
@ControllerAdvice
publicclassMyExceptionHandler{
@ExceptionHandler(UserNotExistException.class)
publicStringhandleException(Exceptione,HttpServletRequestrequest){
Mapmap=newHashMap<>();
//传入我们自己的错误状态码4xx5xx,否则就不会进入定制错误页面的解析流程
/**
*IntegerstatusCode=(Integer)request
.getAttribute("javax.servlet.error.status_code");
*/
request.setAttribute("javax.servlet.error.status_code",400);
map.put("code","user.notexist");
map.put("message",e.getMessage());
//转发给错误处理器MyErrorAttributes
request.setAttribute("ext",map);
//转发到/error进行自适应响应效果处理
return"forward:/error";
}
}
3.定制数据携带出去
出现错误以后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据是由getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
1、完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中;
2、页面上能用的数据,或者是json返回能用的数据都是通过errorAttributes.getErrorAttributes得到;
容器中DefaultErrorAttributes.getErrorAttributes();默认进行数据处理的;
自定义ErrorAttributes
packagecn.jfjb.crud.component;
importorg.springframework.boot.web.servlet.error.DefaultErrorAttributes;
importorg.springframework.stereotype.Component;
importorg.springframework.web.context.request.WebRequest;
importjava.util.Map;
/**
*@authorjohn
*@date2019/11/24-12:13
*/
@Component
publicclassMyErrorAttributesextendsDefaultErrorAttributes{
@Override
publicMapgetErrorAttributes(WebRequestwebRequest,booleanincludeStackTrace){
Mapmap=super.getErrorAttributes(webRequest,includeStackTrace);
//获取自定义处理异常传递的参数
Mapext=(Map)webRequest.getAttribute("ext",0);
map.put("company","atguigu");
map.put("ext",ext);
returnmap;
}
}
4.配置application.yml
server: error: include-exception:true
5.编写4xx.html自定义错误页面
4xx status:[[${status}]]
timestamp:[[${timestamp}]]
exception:[[${exception}]]
message:[[${message}]]