springBoot(5) springBoot的/error的自定义处理

    在springboot项目里,如果没有统一异常处理,或者如果没有处理全面,又或者在springCloud zuul中调用微服务接口出错时,spring会自动把错误转发到默认给/error处理。

    正常情况下,可以配置错误页面来给用户提示错误,如404,500等。但是在前后分离项目中,可能更期望给前台返回一个特定格式的json来展示错误信息。所以可以用代码来自定义异常错误信息。


    /error 端 点 的 实现来源于 Spring Boot 的 org.springframework.boot.autoconfigure.web.BasicErrorController, 它的具体定义如下:

@RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    Map<String, Object> body = getErrorAttributes(request,isincludeStackTrace(request, MediaType.ALL)) ;
    HttpStatus status = getStatus(request);
    return new ResponseEntity<Map<String, Object>>(body, status);}

    通过调用 getErrorAtt豆butes 方法来根据请求参数组织错误信息的返回结果,而这里的 getErrorAtt豆bu七es 方法会将具体组织逻辑委托给 org.springframework.boot.autoconfigure.web.ErrorAttributes接口提供的 ge七ErrorAttributes 来实现。

    在 Spring Boot 的自动化配置机制中,默认会采用 org.springframework.boot.autoconfigure.web.DefaultErrorAttribut作为该接口的实现。

    在spring注册这个bean的时候,使用了注解@ConditionalOnMissingBean(value = ErrorAttributes.class, search =SearchStrategy.CURRENT)

    说明只有在不存在ErrorAttributes的bean的时候,才会使用DefaultErrorAttributes来处理,如果我们可以自定义一个,就可以使用我们的类来处理异常了。

    编写一个类继承DefaultErrorAttributes,他有三个方法:

  1. public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex)
  2. public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace)
  3. public Throwable getError(RequestAttributes requestAttributes)

    他们的执行顺序就如上述顺序。

    我们可以在getErrorAttributes方法中拿到所有的异常信息,展示如下:

{"timestamp":1528190975129,"status":200,"error":"OK","exception":"java.lang.RuntimeException","message":"error............","path":"/a/b"}

    可以在resolveException中拿到异常信息,如果需要返回json,则可以利用response来输出到前台,比如:

    

/* 使用response返回 */
		response.setStatus(HttpStatus.OK.value()); // 设置状态码
		response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
		response.setCharacterEncoding("UTF-8"); // 避免乱码
		response.setHeader("Cache-Control", "no-cache, must-revalidate");

		try {
			response.getWriter().print("json..........");
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.getWriter().close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
    这样,当有异常发生时,就可以在前台收到异常的json信息,而这个也可以代替统一异常处理使用。同时在springCloud zuul中可以用来自定义异常。


猜你喜欢

转载自blog.csdn.net/wangzhanzheng/article/details/80584704