Spring Cloud Gateway过滤器精确控制异常返回(

2021-11-25  本文已影响0人  程序员欣宸

欢迎访问我的GitHub

这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos

本篇概览

在这里插入图片描述

提前小结

  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字段

Spring Cloud Gateway错误处理源码

在这里插入图片描述 在这里插入图片描述
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
        return route(acceptsTextHtml(), this::renderErrorView).andRoute(all(), this::renderErrorResponse);
    }
protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
  // 取出所有错误信息
  Map<String, Object> 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<String, Object> errorAttributes) {
  return (int) errorAttributes.get("status");
}
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
        Map<String, Object> 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<ResponseStatus> 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<ResponseStatus> 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. 终极方案,完全定制返回内容

你不孤单,欣宸原创一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 数据库+中间件系列
  6. DevOps系列

欢迎关注公众号:程序员欣宸

微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界...
https://github.com/zq2599/blog_demos

上一篇 下一篇

猜你喜欢

热点阅读