由于gateway默认的返回码和返回信息不能满足下游微服务的自定义的异常响应码和描述,则需要通过网关透传下游微服务的异常的码值或者至少异常描述信息。

spring cloud gateway给我们留了口子,只需要继承类DefaultErrorWebExceptionHandler,并覆盖相应的接口,并且声明ErrorWebExceptionHandler配置即可,下面贴出代码:

1、 ErrorWebExceptionHandler配置

@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ExceptionHandlerConfiguration {private final ServerProperties serverProperties;private final ApplicationContext applicationContext;private final ResourceProperties resourceProperties;private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;public ExceptionHandlerConfiguration(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;}}

2、自定义DefaultErrorWebExceptionHandler异常处理类

public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {private static Logger logger = LoggerFactory.getLogger(JsonExceptionHandler.class);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 = HttpStatus.INTERNAL_SERVER_ERROR.value();Throwable error = super.getError(request);if (error instanceof org.springframework.cloud.gateway.support.NotFoundException) {code = HttpStatus.NOT_FOUND.value();}
//        return response(code, this.buildMessage(request, error));return response(code, error.getMessage());}/*** 指定响应处理方法为JSON处理的方法* @param errorAttributes*/@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);}/*** 根据code获取对应的HttpStatus* @param errorAttributes*/@Overrideprotected int getHttpStatus(Map<String, Object> errorAttributes) {int statusCode = (int) errorAttributes.get("code");
//        return HttpStatus.valueOf(statusCode);return 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);logger.error(map.toString());return map;}
}

Spring cloud gateway的自定义异常响应相关推荐

  1. Spring Cloud Gateway 自定义网络响应状态码(401,500,503等等)

    近几天打算做一个网关校验的东西,但是发现在使用Gateway的过滤器的时候,没找到设置响应的状态码,网上找了好多也没找到emmmm,不过还好解决了. 直接贴上代码,下面有给出: package com ...

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

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

  3. Spring Cloud Gateway CORS 方案看这篇就够了

    欢迎关注方志朋的博客,回复"666"获面试宝典 在 SpringCloud 项目中,前后端分离目前很常见,在调试时,会遇到两种情况的跨域: 前端页面通过不同域名或IP访问微服务的后 ...

  4. SpringCloud 2020版本教程2:使用spring cloud gateway作为服务网关

    点击关注公众号,Java干货及时送达 Spring Cloud Gateway是Spring Cloud官方推出的第二代网关框架,取代Zuul网关.网关作为流量的,在微服务系统中有着非常作用,网关常见 ...

  5. spring cloud gateway之服务注册与发现

    点击上方"方志朋",选择"置顶或者星标" 你的关注意义重大! 在之前的文章介绍了Spring Cloud Gateway的Predict(断言).Filter( ...

  6. spring cloud gateway之filter篇

    点击上方"方志朋",选择"置顶或者星标" 你的关注意义重大! 在上一篇文章详细的介绍了Gateway的Predict,Predict决定了请求由哪一个路由处理, ...

  7. Spring Cloud Gateway之Predict篇

    Spring Cloud gateway工作流程 在之前的文章的Spring Cloud GateWay初体验中,大家已经对Spring Cloud Gateway的功能有一个初步的认识,网关作为一个 ...

  8. Spring Cloud Gateway 整合阿里 Sentinel网关限流实战!

    前一篇文章介绍了Spring Cloud Gateway的一些基础知识点,今天陈某就来唠一唠网关层面如何做限流? 文章目录如下: 网关如何限流? Spring Cloud Gateway本身自带的限流 ...

  9. 实战 Spring Cloud Gateway 之限流篇

    来源:https://www.aneasystone.com/archives/2020/08/spring-cloud-gateway-current-limiting.html 话说在 Sprin ...

最新文章

  1. 划重点!2020年,这些前沿技术最受关注
  2. php统计播放量_php 怎么统计文章的访问量?
  3. jenkins+maven+ansible实现测试环境完全自动发布
  4. Activity之间切换 以及传值
  5. 【sklearrn学习】朴素贝叶斯
  6. 您的JAX-RS API并非天生就等于:使用动态功能
  7. sendencpac文件能删吗_“手机刷短视频”躺赚?安装自动阅读文件,开机就能挣钱?靠谱吗?...
  8. CentOS修改网络配置
  9. 英特尔“硬盘内存一体化”首款产品正式发布,读写速度超千倍,存储密度扩充十倍...
  10. 七牛云删除图片接口_Thinkphp连接七牛云存储空间删除图片
  11. 【动态规划区间dp】蓝桥2019:最优包含
  12. Hbase 操作工具类
  13. 【Go】使用压缩文件优化io (二)
  14. 「ZJOI2019」麻将
  15. JVM之类的加载与类加载器
  16. 车辆有效信息的识别 车牌车型车颜色 车标识别,基于mallab算法
  17. 绵阳python培训_绵怎么组词
  18. 数字内容产业的七种主要盈利模式
  19. Agent 监控配置说明
  20. pcb二次钻孔_pcb钻孔的注意事项

热门文章

  1. 项目中遇到不善于表达的人,该如何沟通?
  2. Java如何通过WSDL文件来调用这些web service
  3. co11n——生产订单确认的BAPI
  4. PP部分主数据导出SQVI设置
  5. mysql slow time_mysql使用slow log
  6. html固定右侧显示,html+css布局之--左边固定宽,右侧自适应(4种方法)
  7. sql server与java实例_Origin数据处理实例教程50节02040101
  8. oracle 密码文件作用,测试 oracle 密码文件在何时起作用
  9. dataframe在特定列 插入_从插入看mysql存储引擎的区别
  10. Python枚举类型的使用