资讯专栏INFORMATION COLUMN

springboot源码分析系列(四)--web错误处理机制

paney129 / 1990人阅读

摘要:对应的请求信息如下如果是其他客户端请求,如测试,会默认返回数据在之前的文章中介绍过了的自动配置机制,默认错误处理机制也是自动配置其中的一部分。在这个包中加载了所有的自动配置类,其中就是处理异常的机制。

  在我们开发的过程中经常会看到下图这个界面,这是SpringBoot默认出现异常之后给用户抛出的异常处理界面。

  对应的请求信息如下:

  如果是其他客户端请求,如postman测试,会默认返回json数据

{
        "timestamp":"2019-08-06 22:26:16",
        "status":404,
        "error":"Not Found",
        "message":"No message available",
        "path":"/asdad"
}

  在之前的文章中介绍过了SpringBoot的自动配置机制,默认错误处理机制也是自动配置其中的一部分。在spring-boot-autoconfiguration-XXX.jar这个包中加载了所有的自动配置类,其中ErrorMvcAutoConfiguration就是SpringBoot处理异常的机制。

  下面简单的分析一下它的机制

SpringBoot错误处理机制

  首先看一下ErrorMvcAutoConfiguration这个类里面主要起作用的几个方法

/**
 * 绑定一些错误信息
 */
@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException());
}
/**
 * 默认错误处理
 */
@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
    return new BasicErrorController(errorAttributes, this.serverProperties.getError(), this.errorViewResolvers);
}
/**
 * 错误处理页面
 */
@Bean
public ErrorPageCustomizer errorPageCustomizer() {
    return new ErrorPageCustomizer(this.serverProperties, this.dispatcherServletPath);
}

@Configuration
static class DefaultErrorViewResolverConfiguration {

    private final ApplicationContext applicationContext;

    private final ResourceProperties resourceProperties;

    DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext,
            ResourceProperties resourceProperties) {
        this.applicationContext = applicationContext;
        this.resourceProperties = resourceProperties;
    }
    /**
     * 决定去哪个错误页面
     */
    @Bean
    @ConditionalOnBean(DispatcherServlet.class)
    @ConditionalOnMissingBean
    public DefaultErrorViewResolver conventionErrorViewResolver() {
        return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties);
    }

}
errorAttributes

  主要起作用的是下面这个类

org.springframework.boot.web.servlet.error.DefaultErrorAttributes

  这个类会共享很多错误信息,如:

errorAttributes.put("timestamp", new Date());
errorAttributes.put("status", status);
errorAttributes.put("error", HttpStatus.valueOf(status).getReasonPhrase());
errorAttributes.put("errors", result.getAllErrors());
errorAttributes.put("exception", error.getClass().getName());
errorAttributes.put("message", error.getMessage());
errorAttributes.put("trace", stackTrace.toString());
errorAttributes.put("path", path);

  这些信息作为共享信息返回,所以当我们使用模板引擎时,也可以像取出其他参数一样取出。

basicErrorController
//org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController

@Controller
//定义请求路径,如果没有error.path路径,则路径为/error
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {

    //如果支持的格式 text/html
    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = getStatus(request);
        //获取要返回的值
        Map model = Collections
                .unmodifiableMap(getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        //解析错误视图信息,也就是下面1.4中的逻辑
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        //返回视图,如果没有存在的页面模板,则使用默认错误视图模板
        return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
    }

    @RequestMapping
    public ResponseEntity> error(HttpServletRequest request) {
        //如果是接收所有格式的HTTP请求
        Map body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        //响应httpEntity
        return new ResponseEntity<>(body, status);
    }
}

  由上面的源码可知,basicErrorControll主要用于创建请求返回的controller类,并根据http请求可接受的格式不同返回对应的信息。也就是我们在文章的一开始看到的情况,页面请求和接口测试工具请求得到的结果略有差异。

errorPageCustomizer

  errorPageCustomizer这个方法调了同类里面的ErrorPageCustomizer 这个内部类。当遇到错误时,如果没有自定义error.path属性,请求会转发至/error

/**
 * {@link WebServerFactoryCustomizer} that configures the server"s error pages.
 */
private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {

    private final ServerProperties properties;

    private final DispatcherServletPath dispatcherServletPath;

    protected ErrorPageCustomizer(ServerProperties properties, DispatcherServletPath dispatcherServletPath) {
        this.properties = properties;
        this.dispatcherServletPath = dispatcherServletPath;
    }

    @Override
    public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
        //getPath()得到如下地址,如果没有自定义error.path属性,则去/error位置
        //@Value("${error.path:/error}")
        //private String path = "/error";
        ErrorPage errorPage = new ErrorPage(
                this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
        errorPageRegistry.addErrorPages(errorPage);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
conventionErrorViewResolver

  下面的代码只展示部分核心方法

// org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver

public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {

    static {
        Map views = new EnumMap<>(Series.class);
        views.put(Series.CLIENT_ERROR, "4xx");
        views.put(Series.SERVER_ERROR, "5xx");
        SERIES_VIEWS = Collections.unmodifiableMap(views);
    }

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map model) {
        //使用HTTP完整状态码检查是否有页面可以匹配
        ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
        if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
            //使用HTTP状态码第一位匹配初始化中的参数创建视图对象
            modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
        }
        return modelAndView;
    }

    private ModelAndView resolve(String viewName, Map model) {
        // 拼接错误视图路径 /error/{viewName}
        String errorViewName = "error/" + viewName;
        // 使用模板引擎尝试创建视图对象
        TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
                this.applicationContext);
        if (provider != null) {
            return new ModelAndView(errorViewName, model);
        }
        //没有模板引擎,使用静态资源文件夹解析视图
        return resolveResource(errorViewName, model);
    }

    private ModelAndView resolveResource(String viewName, Map model) {
        // 遍历静态资源文件夹,检查是否有存在视图
        for (String location : this.resourceProperties.getStaticLocations()) {
            try {
                Resource resource = this.applicationContext.getResource(location);
                resource = resource.createRelative(viewName + ".html");
                if (resource.exists()) {
                    return new ModelAndView(new HtmlResourceView(resource), model);
                }
            }
            catch (Exception ex) {
            }
        }
        return null;
    }
}

  Thymeleaf对于错误页面的解析如下:

public class ThymeleafTemplateAvailabilityProvider implements TemplateAvailabilityProvider {

    @Override
    public boolean isTemplateAvailable(String view, Environment environment, ClassLoader classLoader,
            ResourceLoader resourceLoader) {
        if (ClassUtils.isPresent("org.thymeleaf.spring5.SpringTemplateEngine", classLoader)) {
            String prefix = environment.getProperty("spring.thymeleaf.prefix", ThymeleafProperties.DEFAULT_PREFIX);
            String suffix = environment.getProperty("spring.thymeleaf.suffix", ThymeleafProperties.DEFAULT_SUFFIX);
            return resourceLoader.getResource(prefix + view + suffix).exists();
        }
        return false;
    }

}

  错误页面首先会检查模板引擎文件夹下的/error/HTTP状态码文件,如果不存在,则去检查模板引擎下的/error/4xx或者/error/5xx文件,如果还不存在,则检查静态资源文件夹下对应的上述文件

自定义异常页面

  刚才分析了异常处理机制是如何工作的,下面我们来自己定义一个异常页面。根据源码分析可以看到,自定义错误页面只需要在模板文件夹下的error文件夹下放置4xx或者5xx文件即可。




    
    
    [[${status}]]
    
    


错误码:[[${status}]]

信息:[[${message}]]

时间:[[${#dates.format(timestamp,"yyyy-MM-dd hh:mm:ss ")}]]

请求路径:[[${path}]]

  随意访问不存在路径得到下图

自定义错误JSON

  根据上面的错误处理机制可以得知,最终返回的JSON信息是从一个map对象转换出来的,只需要自定义map中的值,就可以自定义错误信息的json了。直接重写DefaultErrorAttributes类的 getErrorAttributes 方法即可。

/**
 * 自定义错误信息JSON值
 */
@Component
public class ErrorAttributesCustom extends DefaultErrorAttributes {
    //重写getErrorAttributes方法
    @Override
    public Map getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        //获取原来的响应数据
        Map map = super.getErrorAttributes(webRequest, includeStackTrace);
        String code = map.get("status").toString();
        String message = map.get("error").toString();
        HashMap hashMap = new HashMap<>();
        //添加我们定制的响应数据
        hashMap.put("code", code);
        hashMap.put("message", message);
        return hashMap;
    }
}

  使用postman测试结果如下:

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76103.html

相关文章

  • java篇

    摘要:多线程编程这篇文章分析了多线程的优缺点,如何创建多线程,分享了线程安全和线程通信线程池等等一些知识。 中间件技术入门教程 中间件技术入门教程,本博客介绍了 ESB、MQ、JMS 的一些知识... SpringBoot 多数据源 SpringBoot 使用主从数据源 简易的后台管理权限设计 从零开始搭建自己权限管理框架 Docker 多步构建更小的 Java 镜像 Docker Jav...

    honhon 评论0 收藏0
  • 写这么多系列博客,怪不得找不到女朋友

    摘要:前提好几周没更新博客了,对不断支持我博客的童鞋们说声抱歉了。熟悉我的人都知道我写博客的时间比较早,而且坚持的时间也比较久,一直到现在也是一直保持着更新状态。 showImg(https://segmentfault.com/img/remote/1460000014076586?w=1920&h=1080); 前提 好几周没更新博客了,对不断支持我博客的童鞋们说声:抱歉了!。自己这段时...

    JerryWangSAP 评论0 收藏0
  • Java后端

    摘要:,面向切面编程,中最主要的是用于事务方面的使用。目标达成后还会有去构建微服务,希望大家多多支持。原文地址手把手教程优雅的应用四手把手实现后端搭建第四期 SpringMVC 干货系列:从零搭建 SpringMVC+mybatis(四):Spring 两大核心之 AOP 学习 | 掘金技术征文 原本地址:SpringMVC 干货系列:从零搭建 SpringMVC+mybatis(四):Sp...

    joyvw 评论0 收藏0
  • spring boot - 收藏集 - 掘金

    摘要:引入了新的环境和概要信息,是一种更揭秘与实战六消息队列篇掘金本文,讲解如何集成,实现消息队列。博客地址揭秘与实战二数据缓存篇掘金本文,讲解如何集成,实现缓存。 Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 健康监控 - 掘金Health 信息是从 ApplicationContext 中所有的 HealthIndicator 的 Bean 中收集的, Spring...

    rollback 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<