Springboot 系列(七)Spring Boot web 开发之异常错误处理机制剖析

前言

相信你们在刚开始体验 Springboot 的时候必定会常常碰到这个页面,也就是访问一个不存在的页面的默认返回页面。 css

错误页面
若是是其余客户端请求,如接口测试工具,会默认返回JSON数据。

{
        "timestamp":"2019-01-06 22:26:16",
        "status":404,
        "error":"Not Found",
        "message":"No message available",
        "path":"/asdad"
}
复制代码

很明显,SpringBoot 根据 HTTP 的请求头信息进行了不一样的响应处理。HTTP 相关知识能够参考此处html

1. SpringBoot 异常处理机制

追随 SpringBoot 源码能够分析出默认的错误处理机制。java

// org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
// 绑定一些错误信息 记为 1
	@Bean
	@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
	public DefaultErrorAttributes errorAttributes() {
		return new DefaultErrorAttributes(
				this.serverProperties.getError().isIncludeException());
	}
// 默认处理 /error 记为 2
	@Bean
	@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
	public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
		return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
				this.errorViewResolvers);
	}
// 错误处理页面 记为3
	@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;
		}
// 决定去哪一个错误页面 记为4
		@Bean
		@ConditionalOnBean(DispatcherServlet.class)
		@ConditionalOnMissingBean
		public DefaultErrorViewResolver conventionErrorViewResolver() {
			return new DefaultErrorViewResolver(this.applicationContext,
					this.resourceProperties);
		}

	}

复制代码

结合上面的注释,上面代码里的四个方法就是 Springboot 实现默认返回错误页面主要部分。git

1.1. errorAttributes

errorAttributes直译为错误属性,这个方法确实如此,直接追踪源代码。
代码位于:github

// org.springframework.boot.web.servlet.error.DefaultErrorAttributes
复制代码

这个类里为错误状况共享不少错误信息,如。web

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);
复制代码

这些信息用做共享信息返回,因此当咱们使用模版引擎时,也能够像取出其余参数同样轻松取出。面试

1.2. basicErrorControll

直接追踪 BasicErrorController 的源码内容能够发现下面的一段代码。spring

// 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<String, Object> 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<Map<String, Object>> error(HttpServletRequest request) {
		// 若是是接受全部格式的HTTP请求
        Map<String, Object> body = getErrorAttributes(request,
				isIncludeStackTrace(request, MediaType.ALL));
		HttpStatus status = getStatus(request);
        // 响应HttpEntity
		return new ResponseEntity<>(body, status);
	}  
}
复制代码

由上可知,basicErrorControll 用于建立用于请求返回的 controller类,并根据HTTP请求可接受的格式不一样返回对应的信息,因此在使用浏览器和接口测试工具测试时返回结果存在差别。json

1.3. ererrorPageCustomizer

直接查看方法里的new ErrorPageCustomizer(this.serverProperties, this.dispatcherServletPath);bootstrap

//org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration.ErrorPageCustomizer
	/** * {@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;
		}
		// 注册错误页面
        // this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath())
		@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;
		}

	}

复制代码

由上可知,当遇到错误时,若是没有自定义 error.path 属性,则请求转发至 /error.

1.4. conventionErrorViewResolver

根据上面的代码,一步步深刻查看 SpringBoot 的默认错误处理实现,查看看 conventionErrorViewResolver方法。下面是 DefaultErrorViewResolver 类的部分代码,注释解析。

// org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver
	
// 初始化参数,key 是HTTP状态码第一位。
	static {
		Map<Series, String> 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<String, Object> 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<String, Object> model) {
		// 拼接错误视图路径 /eroor/[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<String, Object> 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 对于错误页面的解析实现。

//org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider
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 文件,若是还不存在,则检查静态资源文件夹下对应的上述文件。

2. 自定义异常页面

通过上面的 SpringBoot 错误机制源码分析,知道当遇到错误状况时候,SpringBoot 会首先返回到模版引擎文件夹下的 /error/HTTP状态码 文件,若是不存在,则检查去模版引擎下的/error/4xx或者 /error/5xx 文件,若是还不存在,则检查静态资源文件夹下对应的上述文件。而且在返回时会共享一些错误信息,这些错误信息能够在模版引擎中直接使用。

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);
复制代码

所以,须要自定义错误页面,只须要在模版文件夹下的 error 文件夹下防止4xx 或者 5xx 文件便可。

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>[[${status}]]</title>
    <!-- Bootstrap core CSS -->
    <link href="/webjars/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body >
<div class="m-5" >
    <p>错误码:[[${status}]]</p>
    <p >信息:[[${message}]]</p>
    <p >时间:[[${#dates.format(timestamp,'yyyy-MM-dd hh:mm:ss ')}]]</p>
    <p >请求路径:[[${path}]]</p>
</div>

</body>
</html>
复制代码

随意访问不存在路径获得。

错误提示

3. 自定义错误JSON

根据上面的 SpringBoot 错误处理原理分析,得知最终返回的 JSON 信息是从一个 map 对象中转换出来的,那么,只要能自定义 map 中的值,就能够自定义错误信息的 json 格式了。直接重写 DefaultErrorAttributes类的 getErrorAttributes 方法便可。

import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

/** * <p> * 自定义错误信息JSON值 * * @Author niujinpeng * @Date 2019/1/7 15:21 */
@Component
public class ErrorAttributesCustom extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
        String code = map.get("status").toString();
        String message = map.get("error").toString();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", code);
        hashMap.put("message", message);
        return hashMap;
    }
}
复制代码

使用 postman 请求测试。

统一异常处理

4. 统一异常处理

使用 @ControllerAdvice 结合@ExceptionHandler 注解能够实现统一的异常处理,@ExceptionHandler注解的类会自动应用在每个被 @RequestMapping 注解的方法。当程序中出现异常时会层层上抛

import lombok.extern.slf4j.Slf4j;
import net.codingme.boot.domain.Response;
import net.codingme.boot.enums.ResponseEnum;
import net.codingme.boot.utils.ResponseUtill;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/** * <p> * 统一的异常处理 * * @Author niujinpeng * @Date 2019/1/7 14:26 */

@Slf4j
@ControllerAdvice
public class ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Response handleException(Exception e) {
        log.info("异常 {}", e);
        if (e instanceof BaseException) {
            BaseException exception = (BaseException) e;
            String code = exception.getCode();
            String message = exception.getMessage();
            return ResponseUtill.error(code, message);
        }
        return ResponseUtill.error(ResponseEnum.UNKNOW_ERROR);
    }
}
复制代码

请求异常页面获得响应以下。

{
 "code": "-1",
 "data": [],
 "message": "未知错误"
}
复制代码

文章代码已经上传到 GitHub Spring Boot Web开发 - 错误机制

<完>

我的网站:www.codingme.net
若是你喜欢这篇文章,能够关注公众号,谢谢支持哟 ❤ 。
关注公众号回复资源能够没有套路的获取全网最火的的 Java 核心知识整理&面试资料。

公众号
相关文章
相关标签/搜索