|
| 1 | +--- |
| 2 | +title: Springboot 系列(七)web 开发之异常错误处理机制剖析 |
| 3 | +toc_number: false |
| 4 | +date: 2019-02-22 08:00:01 |
| 5 | +url: springboot/springboot-07-web-exception |
| 6 | +tags: |
| 7 | + - Springboot |
| 8 | + - Springboot 异常处理 |
| 9 | +categories: |
| 10 | + - Springboot |
| 11 | +--- |
| 12 | + |
| 13 | +## 前言 |
| 14 | + |
| 15 | +相信大家在刚开始体验 Springboot 的时候一定会经常碰到这个页面,也就是访问一个不存在的页面的默认返回页面。 |
| 16 | + |
| 17 | +<!-- more --> |
| 18 | +如果是其他客户端请求,如接口测试工具,会默认返回JSON数据。 |
| 19 | +```json |
| 20 | +{ |
| 21 | + "timestamp":"2019-01-06 22:26:16", |
| 22 | + "status":404, |
| 23 | + "error":"Not Found", |
| 24 | + "message":"No message available", |
| 25 | + "path":"/asdad" |
| 26 | +} |
| 27 | +``` |
| 28 | +很明显,SpringBoot 根据 [HTTP 的请求头信息](https://www.wdbyte.com/2018/07/computer/protocol-http/)进行了不同的响应处理。 |
| 29 | + |
| 30 | +## 1. SpringBoot 异常处理机制 |
| 31 | +追随 SpringBoot 源码可以分析出默认的错误处理机制。 |
| 32 | +```java |
| 33 | +// org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration |
| 34 | +// 绑定一些错误信息 记为 1 |
| 35 | + @Bean |
| 36 | + @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT) |
| 37 | + public DefaultErrorAttributes errorAttributes() { |
| 38 | + return new DefaultErrorAttributes( |
| 39 | + this.serverProperties.getError().isIncludeException()); |
| 40 | + } |
| 41 | +// 默认处理 /error 记为 2 |
| 42 | + @Bean |
| 43 | + @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT) |
| 44 | + public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) { |
| 45 | + return new BasicErrorController(errorAttributes, this.serverProperties.getError(), |
| 46 | + this.errorViewResolvers); |
| 47 | + } |
| 48 | +// 错误处理页面 记为3 |
| 49 | + @Bean |
| 50 | + public ErrorPageCustomizer errorPageCustomizer() { |
| 51 | + return new ErrorPageCustomizer(this.serverProperties, this.dispatcherServletPath); |
| 52 | + } |
| 53 | + @Configuration |
| 54 | + static class DefaultErrorViewResolverConfiguration { |
| 55 | + |
| 56 | + private final ApplicationContext applicationContext; |
| 57 | + |
| 58 | + private final ResourceProperties resourceProperties; |
| 59 | + |
| 60 | + DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext, |
| 61 | + ResourceProperties resourceProperties) { |
| 62 | + this.applicationContext = applicationContext; |
| 63 | + this.resourceProperties = resourceProperties; |
| 64 | + } |
| 65 | +// 决定去哪个错误页面 记为4 |
| 66 | + @Bean |
| 67 | + @ConditionalOnBean(DispatcherServlet.class) |
| 68 | + @ConditionalOnMissingBean |
| 69 | + public DefaultErrorViewResolver conventionErrorViewResolver() { |
| 70 | + return new DefaultErrorViewResolver(this.applicationContext, |
| 71 | + this.resourceProperties); |
| 72 | + } |
| 73 | + |
| 74 | + } |
| 75 | + |
| 76 | +``` |
| 77 | +结合上面的注释,上面代码里的四个方法就是 Springboot 实现默认返回错误页面主要部分。 |
| 78 | +### 1.1. errorAttributes |
| 79 | +`errorAttributes`直译为错误属性,这个方法确实如此,直接追踪源代码。 |
| 80 | +代码位于: |
| 81 | +```java |
| 82 | +// org.springframework.boot.web.servlet.error.DefaultErrorAttributes |
| 83 | +``` |
| 84 | +这个类里为错误情况共享很多错误信息,如。 |
| 85 | +``` |
| 86 | +errorAttributes.put("timestamp", new Date()); |
| 87 | +errorAttributes.put("status", status); |
| 88 | +errorAttributes.put("error", HttpStatus.valueOf(status).getReasonPhrase()); |
| 89 | +errorAttributes.put("errors", result.getAllErrors()); |
| 90 | +errorAttributes.put("exception", error.getClass().getName()); |
| 91 | +errorAttributes.put("message", error.getMessage()); |
| 92 | +errorAttributes.put("trace", stackTrace.toString()); |
| 93 | +errorAttributes.put("path", path); |
| 94 | +``` |
| 95 | +这些信息用作共享信息返回,所以当我们使用模版引擎时,也可以像取出其他参数一样轻松取出。 |
| 96 | +### 1.2. basicErrorControll |
| 97 | +直接追踪 `BasicErrorController` 的源码内容可以发现下面的一段代码。 |
| 98 | +```java |
| 99 | +// org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController |
| 100 | +@Controller |
| 101 | +// 定义请求路径,如果没有error.path路径,则路径为/error |
| 102 | +@RequestMapping("${server.error.path:${error.path:/error}}") |
| 103 | +public class BasicErrorController extends AbstractErrorController { |
| 104 | + |
| 105 | + // 如果支持的格式 text/html |
| 106 | + @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) |
| 107 | + public ModelAndView errorHtml(HttpServletRequest request, |
| 108 | + HttpServletResponse response) { |
| 109 | + HttpStatus status = getStatus(request); |
| 110 | + // 获取要返回的值 |
| 111 | + Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes( |
| 112 | + request, isIncludeStackTrace(request, MediaType.TEXT_HTML))); |
| 113 | + response.setStatus(status.value()); |
| 114 | + // 解析错误视图信息,也就是下面1.4中的逻辑 |
| 115 | + ModelAndView modelAndView = resolveErrorView(request, response, status, model); |
| 116 | + // 返回视图,如果没有存在的页面模版,则使用默认错误视图模版 |
| 117 | + return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); |
| 118 | + } |
| 119 | + |
| 120 | + @RequestMapping |
| 121 | + public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { |
| 122 | + // 如果是接受所有格式的HTTP请求 |
| 123 | + Map<String, Object> body = getErrorAttributes(request, |
| 124 | + isIncludeStackTrace(request, MediaType.ALL)); |
| 125 | + HttpStatus status = getStatus(request); |
| 126 | + // 响应HttpEntity |
| 127 | + return new ResponseEntity<>(body, status); |
| 128 | + } |
| 129 | +} |
| 130 | +``` |
| 131 | +由上可知,`basicErrorControll` 用于创建用于请求返回的 `controller`类,并根据HTTP请求可接受的格式不同返回对应的信息,所以在使用浏览器和接口测试工具测试时返回结果存在差异。 |
| 132 | +### 1.3. ererrorPageCustomizer |
| 133 | +直接查看方法里的`new ErrorPageCustomizer(this.serverProperties, this.dispatcherServletPath);` |
| 134 | +```java |
| 135 | +//org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration.ErrorPageCustomizer |
| 136 | + /** |
| 137 | + * {@link WebServerFactoryCustomizer} that configures the server's error pages. |
| 138 | + */ |
| 139 | + private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered { |
| 140 | + |
| 141 | + private final ServerProperties properties; |
| 142 | + |
| 143 | + private final DispatcherServletPath dispatcherServletPath; |
| 144 | + |
| 145 | + protected ErrorPageCustomizer(ServerProperties properties, |
| 146 | + DispatcherServletPath dispatcherServletPath) { |
| 147 | + this.properties = properties; |
| 148 | + this.dispatcherServletPath = dispatcherServletPath; |
| 149 | + } |
| 150 | + // 注册错误页面 |
| 151 | + // this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()) |
| 152 | + @Override |
| 153 | + public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { |
| 154 | + //getPath()得到如下地址,如果没有自定义error.path属性,则去/error位置 |
| 155 | + //@Value("${error.path:/error}") |
| 156 | + //private String path = "/error"; |
| 157 | + ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath |
| 158 | + .getRelativePath(this.properties.getError().getPath())); |
| 159 | + errorPageRegistry.addErrorPages(errorPage); |
| 160 | + } |
| 161 | + |
| 162 | + @Override |
| 163 | + public int getOrder() { |
| 164 | + return 0; |
| 165 | + } |
| 166 | + |
| 167 | + } |
| 168 | + |
| 169 | +``` |
| 170 | +由上可知,当遇到错误时,如果没有自定义 `error.path` 属性,则请求转发至 `/error`. |
| 171 | +### 1.4. conventionErrorViewResolver |
| 172 | +根据上面的代码,一步步深入查看 SpringBoot 的默认错误处理实现,查看看 `conventionErrorViewResolver`方法。下面是 DefaultErrorViewResolver 类的部分代码,注释解析。 |
| 173 | +```java |
| 174 | +// org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver |
| 175 | + |
| 176 | +// 初始化参数,key 是HTTP状态码第一位。 |
| 177 | + static { |
| 178 | + Map<Series, String> views = new EnumMap<>(Series.class); |
| 179 | + views.put(Series.CLIENT_ERROR, "4xx"); |
| 180 | + views.put(Series.SERVER_ERROR, "5xx"); |
| 181 | + SERIES_VIEWS = Collections.unmodifiableMap(views); |
| 182 | + } |
| 183 | + @Override |
| 184 | + public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, |
| 185 | + Map<String, Object> model) { |
| 186 | + // 使用HTTP完整状态码检查是否有页面可以匹配 |
| 187 | + ModelAndView modelAndView = resolve(String.valueOf(status.value()), model); |
| 188 | + if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) { |
| 189 | + // 使用 HTTP 状态码第一位匹配初始化中的参数创建视图对象 |
| 190 | + modelAndView = resolve(SERIES_VIEWS.get(status.series()), model); |
| 191 | + } |
| 192 | + return modelAndView; |
| 193 | + } |
| 194 | + |
| 195 | + |
| 196 | + private ModelAndView resolve(String viewName, Map<String, Object> model) { |
| 197 | + // 拼接错误视图路径 /eroor/[viewname] |
| 198 | + String errorViewName = "error/" + viewName; |
| 199 | + // 使用模版引擎尝试创建视图对象 |
| 200 | + TemplateAvailabilityProvider provider = this.templateAvailabilityProviders |
| 201 | + .getProvider(errorViewName, this.applicationContext); |
| 202 | + if (provider != null) { |
| 203 | + return new ModelAndView(errorViewName, model); |
| 204 | + } |
| 205 | + // 没有模版引擎,使用静态资源文件夹解析视图 |
| 206 | + return resolveResource(errorViewName, model); |
| 207 | + } |
| 208 | + |
| 209 | + private ModelAndView resolveResource(String viewName, Map<String, Object> model) { |
| 210 | + // 遍历静态资源文件夹,检查是否有存在视图 |
| 211 | + for (String location : this.resourceProperties.getStaticLocations()) { |
| 212 | + try { |
| 213 | + Resource resource = this.applicationContext.getResource(location); |
| 214 | + resource = resource.createRelative(viewName + ".html"); |
| 215 | + if (resource.exists()) { |
| 216 | + return new ModelAndView(new HtmlResourceView(resource), model); |
| 217 | + } |
| 218 | + } |
| 219 | + catch (Exception ex) { |
| 220 | + } |
| 221 | + } |
| 222 | + return null; |
| 223 | + } |
| 224 | +``` |
| 225 | +而 Thymeleaf 对于错误页面的解析实现。 |
| 226 | +```java |
| 227 | +//org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider |
| 228 | +public class ThymeleafTemplateAvailabilityProvider |
| 229 | + implements TemplateAvailabilityProvider { |
| 230 | + @Override |
| 231 | + public boolean isTemplateAvailable(String view, Environment environment, |
| 232 | + ClassLoader classLoader, ResourceLoader resourceLoader) { |
| 233 | + if (ClassUtils.isPresent("org.thymeleaf.spring5.SpringTemplateEngine", |
| 234 | + classLoader)) { |
| 235 | + String prefix = environment.getProperty("spring.thymeleaf.prefix", |
| 236 | + ThymeleafProperties.DEFAULT_PREFIX); |
| 237 | + String suffix = environment.getProperty("spring.thymeleaf.suffix", |
| 238 | + ThymeleafProperties.DEFAULT_SUFFIX); |
| 239 | + return resourceLoader.getResource(prefix + view + suffix).exists(); |
| 240 | + } |
| 241 | + return false; |
| 242 | + } |
| 243 | +} |
| 244 | +``` |
| 245 | +从而我们可以得知,错误页面首先会检查`模版引擎`文件夹下的 `/error/HTTP状态码` 文件,如果不存在,则检查去模版引擎下的`/error/4xx`或者 `/error/5xx` 文件,如果还不存在,则检查`静态资源`文件夹下对应的上述文件。 |
| 246 | +## 2. 自定义异常页面 |
| 247 | +经过上面的 SpringBoot 错误机制源码分析,知道当遇到错误情况时候,SpringBoot 会首先返回到`模版引擎`文件夹下的 `/error/HTTP`状态码 文件,如果不存在,则检查去模版引擎下的`/error/4xx`或者 `/error/5xx` 文件,如果还不存在,则检查`静态资源`文件夹下对应的上述文件。并且在返回时会共享一些错误信息,这些错误信息可以在模版引擎中直接使用。 |
| 248 | +```java |
| 249 | +errorAttributes.put("timestamp", new Date()); |
| 250 | +errorAttributes.put("status", status); |
| 251 | +errorAttributes.put("error", HttpStatus.valueOf(status).getReasonPhrase()); |
| 252 | +errorAttributes.put("errors", result.getAllErrors()); |
| 253 | +errorAttributes.put("exception", error.getClass().getName()); |
| 254 | +errorAttributes.put("message", error.getMessage()); |
| 255 | +errorAttributes.put("trace", stackTrace.toString()); |
| 256 | +errorAttributes.put("path", path); |
| 257 | +``` |
| 258 | +因此,需要自定义错误页面,只需要在模版文件夹下的 error 文件夹下防止4xx 或者 5xx 文件即可。 |
| 259 | +```html |
| 260 | +<!doctype html> |
| 261 | +<html lang="en" xmlns:th="http://www.thymeleaf.org"> |
| 262 | +<head> |
| 263 | + <meta charset="UTF-8"> |
| 264 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 265 | + <title>[[${status}]]</title> |
| 266 | + <!-- Bootstrap core CSS --> |
| 267 | + <link href="/webjars/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"> |
| 268 | +</head> |
| 269 | +<body > |
| 270 | +<div class="m-5" > |
| 271 | + <p>错误码:[[${status}]]</p> |
| 272 | + <p >信息:[[${message}]]</p> |
| 273 | + <p >时间:[[${#dates.format(timestamp,'yyyy-MM-dd hh:mm:ss ')}]]</p> |
| 274 | + <p >请求路径:[[${path}]]</p> |
| 275 | +</div> |
| 276 | + |
| 277 | +</body> |
| 278 | +</html> |
| 279 | +``` |
| 280 | +随意访问不存在路径得到。 |
| 281 | + |
| 282 | +发现错误页面已经跳转到我们的自定义页面。 |
| 283 | +## 3. 自定义错误JSON |
| 284 | +根据上面的 SpringBoot 错误处理原理分析,得知最终返回的 JSON 信息是从一个 map 对象中转换出来的,那么,只要能自定义 map 中的值,就可以自定义错误信息的 json 格式了。直接重写 `DefaultErrorAttributes`类的 `getErrorAttributes` 方法即可。 |
| 285 | +```java |
| 286 | +import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; |
| 287 | +import org.springframework.stereotype.Component; |
| 288 | +import org.springframework.web.context.request.WebRequest; |
| 289 | + |
| 290 | +import java.util.HashMap; |
| 291 | +import java.util.Map; |
| 292 | + |
| 293 | +/** |
| 294 | + * <p> |
| 295 | + * 自定义错误信息JSON值 |
| 296 | + * |
| 297 | + * @Author niujinpeng |
| 298 | + * @Date 2019/1/7 15:21 |
| 299 | + */ |
| 300 | +@Component |
| 301 | +public class ErrorAttributesCustom extends DefaultErrorAttributes { |
| 302 | + |
| 303 | + @Override |
| 304 | + public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { |
| 305 | + Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace); |
| 306 | + String code = map.get("status").toString(); |
| 307 | + String message = map.get("error").toString(); |
| 308 | + HashMap<String, Object> hashMap = new HashMap<>(); |
| 309 | + hashMap.put("code", code); |
| 310 | + hashMap.put("message", message); |
| 311 | + return hashMap; |
| 312 | + } |
| 313 | +} |
| 314 | +``` |
| 315 | +使用 postman 请求测试。 |
| 316 | + |
| 317 | + |
| 318 | +## 4. 统一异常处理 |
| 319 | +使用 `@ControllerAdvice` 结合`@ExceptionHandler` 注解可以实现统一的异常处理,`@ExceptionHandler `注解的类会自动应用在每一个被 `@RequestMapping` 注解的方法。当程序中出现异常时会层层上抛 |
| 320 | +```java |
| 321 | +import lombok.extern.slf4j.Slf4j; |
| 322 | +import net.codingme.boot.domain.Response; |
| 323 | +import net.codingme.boot.enums.ResponseEnum; |
| 324 | +import net.codingme.boot.utils.ResponseUtill; |
| 325 | +import org.springframework.web.bind.annotation.ControllerAdvice; |
| 326 | +import org.springframework.web.bind.annotation.ExceptionHandler; |
| 327 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 328 | + |
| 329 | +import javax.servlet.http.HttpServletRequest; |
| 330 | + |
| 331 | +/** |
| 332 | + * <p> |
| 333 | + * 统一的异常处理 |
| 334 | + * |
| 335 | + * @Author niujinpeng |
| 336 | + * @Date 2019/1/7 14:26 |
| 337 | + */ |
| 338 | + |
| 339 | +@Slf4j |
| 340 | +@ControllerAdvice |
| 341 | +public class ExceptionHandle { |
| 342 | + |
| 343 | + @ResponseBody |
| 344 | + @ExceptionHandler(Exception.class) |
| 345 | + public Response handleException(Exception e) { |
| 346 | + log.info("异常 {}", e); |
| 347 | + if (e instanceof BaseException) { |
| 348 | + BaseException exception = (BaseException) e; |
| 349 | + String code = exception.getCode(); |
| 350 | + String message = exception.getMessage(); |
| 351 | + return ResponseUtill.error(code, message); |
| 352 | + } |
| 353 | + return ResponseUtill.error(ResponseEnum.UNKNOW_ERROR); |
| 354 | + } |
| 355 | +} |
| 356 | +``` |
| 357 | +请求异常页面得到响应如下。 |
| 358 | +```json |
| 359 | +{ |
| 360 | + "code": "-1", |
| 361 | + "data": [], |
| 362 | + "message": "未知错误" |
| 363 | +} |
| 364 | +``` |
| 365 | +文章代码已经上传到 GitHub [Spring Boot Web开发 - 错误机制](https://github.com/niumoo/springboot/tree/master/springboot-web-error)。 |
0 commit comments