Spring Cloud Gateway中的全局异常处理不能直接用@ControllerAdvice来处理,通过跟踪异常信息的抛出,找到对应的源码,自定义一些处理逻辑来符合业务的需求。

网关都是给接口做代理转发的,后端对应的都是REST API,返回数据格式都是JSON。如果不做处理,当发生异常时,Gateway默认给出的错误信息是页面,不方便前端进行异常处理。

需要对异常信息进行处理,返回JSON格式的数据给客户端。下面先看实现的代码,后面再跟大家讲下需要注意的地方。

自定义异常处理逻辑:

package com.cxytiandi.gateway.exception;import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;/*** 自定义异常处理* * <p>异常时用JSON代替HTML异常信息<p>* * @author yinjihuan**/
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {    public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {        super(errorAttributes, resourceProperties, errorProperties, applicationContext);}    /*** 获取异常属性*/@Overrideprotected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {        int code = 500;Throwable error = super.getError(request);        if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {code = 404;}        return response(code, this.buildMessage(request, error));}    /*** 指定响应处理方法为JSON处理的方法* @param errorAttributes*/@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);}    /*** 根据code获取对应的HttpStatus* @param errorAttributes*/@Overrideprotected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {        int statusCode = (int) errorAttributes.get("code");        return HttpStatus.valueOf(statusCode);}    /*** 构建异常信息* @param request* @param ex* @return*/private String buildMessage(ServerRequest request, Throwable ex) {StringBuilder message = new StringBuilder("Failed to handle request [");message.append(request.methodName());message.append(" ");message.append(request.uri());message.append("]");        if (ex != null) {message.append(": ");message.append(ex.getMessage());}        return message.toString();}    /*** 构建返回的JSON数据格式* @param status        状态码* @param errorMessage  异常信息* @return*/public static Map<String, Object> response(int status, String errorMessage) {Map<String, Object> map = new HashMap<>();map.put("code", status);map.put("message", errorMessage);map.put("data", null);        return map;}}

覆盖默认的配置:

package com.cxytiandi.gateway.exception;import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;/*** 覆盖默认的异常处理* * @author yinjihuan**/
@Configuration@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfiguration {    private final ServerProperties serverProperties;    private final ApplicationContext applicationContext;    private final ResourceProperties resourceProperties;    private final List<ViewResolver> viewResolvers;    private final ServerCodecConfigurer serverCodecConfigurer;    public ErrorHandlerConfiguration(ServerProperties serverProperties,ResourceProperties resourceProperties,ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer,ApplicationContext applicationContext) { this.serverProperties = serverProperties;        this.applicationContext = applicationContext;        this.resourceProperties = resourceProperties;        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);           this.serverCodecConfigurer = serverCodecConfigurer;}    @Bean@Order(Ordered.HIGHEST_PRECEDENCE)    public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(errorAttributes, this.resourceProperties, this.serverProperties.getError(), this.applicationContext);exceptionHandler.setViewResolvers(this.viewResolvers);exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());return exceptionHandler;}}

注意点

  • 异常时如何返回JSON而不是HTML?

在org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler中的getRoutingFunction()方法就是控制返回格式的,原代码如下:

@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {       return RouterFunctions.route(acceptsTextHtml(), this::renderErrorView).andRoute(RequestPredicates.all(), this::renderErrorResponse);
}

这边优先是用HTML来显示的,想用JSON的改下就可以了,如下:

protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {       return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
  • getHttpStatus需要重写

原始的方法是通过status来获取对应的HttpStatus的,代码如下:

protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {      int statusCode = (int) errorAttributes.get("status");      return HttpStatus.valueOf(statusCode);
}

如果我们定义的格式中没有status字段的话,这么就会报错,找不到对应的响应码,要么返回数据格式中增加status子段,要么重写,我这边返回的是code,所以要重写,代码如下:

@Override
protected HttpStatus getHttpStatus(Map<String, Object> errorAttributes) {    int statusCode = (int) errorAttributes.get("code");    return HttpStatus.valueOf(statusCode);
}

Spring Cloud Gateway的全局异常处理相关推荐

  1. java 配置全局过滤器,如何为Spring Cloud Gateway加上全局过滤器

    既然是一个网关.那么全局过滤器肯定是少不了的一个存在.像是鉴权.认证啥的不可能每个服务都做一次,一般都是在网关处就搞定了. Zuul他就有很强大的过滤器体系来给人使用. Gateway当然也不会差这么 ...

  2. 实战干货!Spring Cloud Gateway 整合 OAuth2.0 实现分布式统一认证授权!

    今天这篇文章介绍一下Spring Cloud Gateway整合OAuth2.0实现认证授权,涉及到的知识点有点多,有不清楚的可以看下陈某的往期文章. 文章目录如下: 微服务认证方案 微服务认证方案目 ...

  3. 微服务网关spring cloud gateway入门详解

    1.API网关 API 网关是一个处于应用程序或服务( REST API 接口服务)之前的系统,用来管理授权.访问控制和流量限制等,这样 REST API 接口服务就被 API 网关保护起来,对所有的 ...

  4. Spring Cloud Gateway 解决跨域问题

      注:文中的解决方案在 Spring Cloud 2021.0.4.Spring Boot 2.7.4 版本中得到验证,完美解决,其他版本可参考   请求流程如下图:通过nginx反向代理到网关,在 ...

  5. Spring Cloud Gateway中异常处理

    Spring Cloud Gateway中异常处理 参考文章: (1)Spring Cloud Gateway中异常处理 (2)https://www.cnblogs.com/viaiu/p/1040 ...

  6. spring cloud gateway跨域全局CORS配置

    在Spring 5 Webflux中,配置CORS,可以通过自定义WebFilter实现: 注:此种写法需真实跨域访问,监控header中才会带相应属性. 代码实现方式 import org.spri ...

  7. spring cloud gateway集成hystrix全局断路器

    pom.xml添加依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifact ...

  8. Spring Cloud Gateway 源码解析(4)-- filter

    文章目录 绑定Filter HandlerMapping Filter GatewayFilterChain FilteringWebHandler GlobalFilter实例化 GatewayFi ...

  9. 【Spring Cloud Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权

    一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间这里只贴出关键部分代码的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证 ...

最新文章

  1. 成为单片机高手必知的三个重要步骤(干货分享)
  2. [react] 举例说明在react中怎么使用样式
  3. java读取gpx文件,从Leaflet导出GPX文件
  4. java把对象转成图片格式转换器安卓版,java 万能图片格式转换
  5. linux定时监控端口并重新启动shell脚本命令
  6. 创建mysql制定字符集语句_创建数据库指定字符集语句
  7. jmeter中控制器3个请求其中一个访问不到_性能测试干货丨盘点JMeter常见的逻辑控制器...
  8. Django UnicodeEncodeError解决
  9. 【转】string.Format对C#字符串格式化
  10. Maple公式推导教程
  11. 【华为机试题 HJ102】字符统计
  12. BZOJ5336:[TJOI2018]游园会——题解
  13. using runtime html4,为什么我不能在C#中引用System.Runtime.Serialization.Json
  14. JVM 重点知识点总结
  15. 设置了相对定位relative之后,改变top值,如何去掉多余空白?
  16. python之Matplotlib
  17. 至简播放器ffplay工作原理
  18. 专家齐议尘肺病农民救助难点
  19. 【问题思考总结】一个大于0的数乘以无穷大一定是无穷大吗?【关于定点和动点,数和函数,定区间和变区间的辨析】
  20. matlab单相桥式全控整流电路仿真

热门文章

  1. 《Web前端工程师修炼之道(原书第4版)》——我该从哪里开始呢
  2. CCF NOI1010 邮寄包裹
  3. linux之heartbeat高可用的简单配置
  4. 通过severlet获取请求头信息
  5. 添加nginx为系统服务(service nginx start/stop/restart)
  6. objective-c 多媒体 音乐播放
  7. 解惑 [1, 2, 3].map(parseInt) 为何返回[1,NaN,NaN]
  8. 某大型国企技术平台建设
  9. Ubuntu 安装配置 MySql
  10. 【Tree】Prim算法思想与步骤