Spring Cloud Gateway过滤器精确控制异常返回(分析篇)

欢迎访问我的GitHub

本篇概览

提前小结

  1. Spring Cloud Gateway应用中,有个ErrorAttributes类型的bean,它的getErrorAttributes方法返回了一个map
  2. 应用抛出异常时,返回码来自上述map的status的值,返回body是整个map序列化的结果
  3. 默认情况下ErrorAttributes的实现类是DefaultErrorAttributes
  1. 先看异常对象是不是ResponseStatusException类型
  2. 如果是ResponseStatusException类型,就调用异常对象的getStatus方法作为返回值
  3. 如果不是ResponseStatusException类型,再看异常类有没有ResponseStatus注解,
  4. 如果有,就取注解的code属性作为返回值
  5. 如果异常对象既不是ResponseStatusException类型,也没有ResponseStatus注解,就返回500
  1. 异常对象是不是BindingResult类型
  2. 如果不是BindingResult类型,就看是不是ResponseStatusException类型
  3. 如果是,就用getReason作为返回值
  4. 如果也不是ResponseStatusException类型,就看异常类有没有ResponseStatus注解,如果有就取该注解的reason属性作为返回值
  5. 如果通过注解取得的reason也无效,就返回异常的getMessage字段
  6. 上述内容就是本篇精华,但是并未包含分析过程,如果您对Spring Cloud源码感兴趣,请允许欣宸陪伴您来一次短暂的源码阅读之旅

Spring Cloud Gateway错误处理源码

@Override
protected RouterFunction getRoutingFunction(ErrorAttributes errorAttributes) {
		return route(acceptsTextHtml(), this::renderErrorView).andRoute(all(), this::renderErrorResponse);
	}
protected Mono renderErrorResponse(ServerRequest request) {
  // 取出所有错误信息
  Map error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
  
  // 构造返回的所有信息 
  return ServerResponse
           // 控制返回码
           .status(getHttpStatus(error))
           // 控制返回ContentType
           .contentType(MediaType.APPLICATION_JSON)
           // 控制返回内容
           .body(BodyInserters.fromValue(error));
}
  1. 返回给调用方的状态码,取决于getHttpStatus方法的返回值
  2. 返回给调用方的body,取决于error的内容
protected int getHttpStatus(Map errorAttributes) {
  return (int) errorAttributes.get("status");
}
public Map getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        Map errorAttributes = this.getErrorAttributes(request, options.isIncluded(Include.STACK_TRACE));
        if (Boolean.TRUE.equals(this.includeException)) {
            options = options.including(new Include[]{Include.EXCEPTION});
        }

        if (!options.isIncluded(Include.EXCEPTION)) {
            errorAttributes.remove("exception");
        }

        if (!options.isIncluded(Include.STACK_TRACE)) {
            errorAttributes.remove("trace");
        }

        if (!options.isIncluded(Include.MESSAGE) && errorAttributes.get("message") != null) {
            errorAttributes.put("message", "");
        }

        if (!options.isIncluded(Include.BINDING_ERRORS)) {
            errorAttributes.remove("errors");
        }

        return errorAttributes;
    }
  1. 返回码来自determineHttpStatus的返回
  2. message字段来自determineMessage的返回
private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation responseStatusAnnotation) {
        // 异常对象是不是ResponseStatusException类型
        return error instanceof ResponseStatusException 
        // 如果是ResponseStatusException类型,就调用异常对象的getStatus方法作为返回值
        ? ((ResponseStatusException)error).getStatus() 
        // 如果不是ResponseStatusException类型,再看异常类有没有ResponseStatus注解,
        // 如果有,就取注解的code属性作为返回值
        : (HttpStatus)responseStatusAnnotation.getValue("code", HttpStatus.class)
        // 如果异常对象既不是ResponseStatusException类型,也没有ResponseStatus注解,就返回500
        .orElse(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    private String determineMessage(Throwable error, MergedAnnotation responseStatusAnnotation) {
        // 异常对象是不是BindingResult类型
        if (error instanceof BindingResult) {
            // 如果是,就用getMessage作为返回值
            return error.getMessage();
        } 
        // 如果不是BindingResult类型,就看是不是ResponseStatusException类型
        else if (error instanceof ResponseStatusException) {
            // 如果是,就用getReason作为返回值
            return ((ResponseStatusException)error).getReason();
        } else {
            // 如果也不是ResponseStatusException类型,
            // 就看异常类有没有ResponseStatus注解,如果有就取该注解的reason属性作为返回值
            String reason = (String)responseStatusAnnotation.getValue("reason", String.class).orElse("");
            if (StringUtils.hasText(reason)) {
                return reason;
            } else {
                // 如果通过注解取得的reason也无效,就返回异常的getMessage字段
                return error.getMessage() != null ? error.getMessage() : "";
            }
        }
    }
  1. 直接了当,控制返回码和body中的error字段
  2. 小小拦路虎,见招拆招
  3. 简单易用,通过注解控制返回信息
  4. 终极方案,完全定制返回内容

欢迎关注头条号:程序员欣宸

展开阅读全文

页面更新:2024-05-11

标签:异常   注解   字段   过滤器   小结   精确   源码   属性   对象   类型   方法   内容

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top