您的位置:首页 > 编程语言 > Java开发

SpringBoot_错误处理机制

2020-03-29 19:21 309 查看

SpringBoot

默认错误处理机制:

错误演示:

浏览器页面请求: 返回错误页面,请求头类型 text/html

其他客户端请求: 响应 json 数据;

原理:

参照ErrorMVCAutoConfiguration,错误处理的自动配置;

给容器添加以下组件:

DefaultErrorAttributes: 帮助在页面共享信息,DefaultErrorAttributes.getErrorAttributes() 是默认进行数据处理的;

@Bean
@ConditionalOnMissingBean(value = {ErrorAttributes.class},search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException());
}
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = new LinkedHashMap();
errorAttributes.put("timestamp", new Date());
this.addStatus(errorAttributes, webRequest);
this.addErrorDetails(errorAttributes, webRequest, includeStackTrace);
this.addPath(errorAttributes, webRequest);
return errorAttributes;
}
页面能获取的信息
timestamp 时间戳
status 状态码
error 错误提示
exception 异常对象
message 异常消息
errors JSR303数据校验的错误

BasicErrorController: 处理默认 /error 请求;

@Bean
@ConditionalOnMissingBean( value = {ErrorController.class},search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes, ObjectProvider<ErrorViewResolver> errorViewResolvers) {
return new BasicErrorController(errorAttributes, this.serverProperties.getError(), (List)errorViewResolvers.orderedStream().collect(Collectors.toList()));
}
@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {

......

@RequestMapping(produces = {"text/html"})     //产生html数据,浏览器发送的请求采用这个方法处理
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
HttpStatus status = this.getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());

//找寻页面作为错误页面;包含页面地址和页面内容
ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
return modelAndView != null ? modelAndView : new ModelAndView("error", model);
}

@RequestMapping       //产生json数据,其他客户端采用这个方法处理
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = this.getStatus(request);
if (status == HttpStatus.NO_CONTENT) {
return new ResponseEntity(status);
} else {
Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
return new ResponseEntity(body, status);
}
}
}
protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
Iterator var5 = this.errorViewResolvers.iterator();

ModelAndView modelAndView;
//采用 do while 循环,所有的ErrorViewResolver得到ModelAndView
do {
if (!var5.hasNext()) {
return null;
}

ErrorViewResolver resolver = (ErrorViewResolver)var5.next();
modelAndView = resolver.resolveErrorView(request, status, model);
} while(modelAndView == null);

return modelAndView;
}

ErrorPageCustomizer: 当系统出现4xx或者5xx之类的错误,ErrorPageCustomizer 生效,进行错误响应规则的定制;

@Bean
public ErrorMvcAutoConfiguration.ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath dispatcherServletPath) {
return new ErrorMvcAutoConfiguration.ErrorPageCustomizer(this.serverProperties, dispatcherServletPath);
}
private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
...
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {

ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(new ErrorPage[]{errorPage});
}
...
}
public class ErrorProperties {
@Value("${error.path:/error}")
private String path = "/error"; //系统出现错误以后,来到error请求进行处理

public String getPath() {
return this.path;
}
...
}

DefaultErrorViewResolver:DefaultErrorViewResolver进行解析,得到错误响应页面;

@Configuration(proxyBeanMethods = false)
static class DefaultErrorViewResolverConfiguration {
...

DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext, ResourceProperties resourceProperties) {
this.applicationContext = applicationContext;
this.resourceProperties = resourceProperties;
}

@Bean
@ConditionalOnBean({DispatcherServlet.class})
@ConditionalOnMissingBean({ErrorViewResolver.class})
DefaultErrorViewResolver conventionErrorViewResolver() {
return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties);
}
}
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
}

return modelAndView;
}

private ModelAndView resolve(String viewName, Map<String, Object> model) {
//默认SpringBoot可以去找到一个页面, error/404
String errorViewName = "error/" + viewName;
//模板引擎可以解析这个页面地址就用模板引擎解析
TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
/**
* 模板引擎可用的情况下返回到errorViewName指定的视图地址
* 模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
*/
return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
}

private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
String[] var3 = this.resourceProperties.getStaticLocations();
int var4 = var3.length;

for(int var5 = 0; var5 < var4; ++var5) {
String location = var3[var5];

try {
Resource resource = this.applicationContext.getResource(location);
resource = resource.createRelative(viewName + ".html");
if (resource.exists()) {
return new ModelAndView(new DefaultErrorViewResolver.HtmlResourceView(resource), model);
}
} catch (Exception var8) {
;
}
}

return null;
}

定制错误响应:

定制错误页面响应:

模板引擎文件夹下有: 将错误页面命名为错误状态码.html ,放在模板引擎文件夹下的error文件夹里面,发生此状态码的错误就会来到对应的页面;我们可以使用4xx5xx作为错误页面的文件名来匹配这种类型的所有错误,优先寻找精确的状态码.html;

模板引擎文件夹下没有,静态资源文件夹下有: 放在静态资源文件夹下的error文件夹里面;

模板引擎文件夹下没有,静态资源文件夹下没有: 默认来到SpringBoot默认的错误提示页面;

示例:

注意点:获取不到异常类型的情况,在配置文件中添加 server.error.include-exception=true

定制错误json数据响应:

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

@ControllerAdvice  //使用 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;
}
}
注意点:这种写法,浏览器客户端返回的都是json

转发到/error进行自适应响应效果处理:

@ControllerAdvice //使用 ControllerAdvice注解 定义成为异常处理器组件
public class MyExceptionHandler {

@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","用户出错啦");

request.setAttribute("ext",map);
//转发到/error
return "forward:/error";
}
}
注意点:此时在客户端,仍然不会显示 code:user.notexist 和 message:用户出错啦 ;

定制json数据携带展示:

可以通过自定义ErrorAttributes改变需要返回的内容,实现自适应的响应;

//给容器中加入我们自己定义的ErrorAttributes,而不使用默认配置
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {

//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
map.put("company","yp");

//自己的异常处理器携带的数据
Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0); // 0 代表从REQUEST域 获取, 1 代表从 SESSION域 获取
map.put("ext",ext);
return map;
}
}

//定义构造器,否则浏览器页面不能正常获取 exception
public MyErrorAttributes() {
super(true);
}

最终效果图:

  • 点赞
  • 收藏
  • 分享
  • 文章举报
Running_lemon 发布了14 篇原创文章 · 获赞 0 · 访问量 484 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: