版本: Spring Cloud 2020.0.3

常见的方法有 实现自己的 DefaultErrorWebExceptionHandler 或 仅实现ErrorAttributes.

方法1: ErrorWebExceptionHandler (仅供示意)

自定义一个 GlobalErrorAttributes:


@Component
public class GlobalErrorAttributes extends DefaultErrorAttributes{ @Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Throwable error = super.getError(request); Map<String, Object> map = super.getErrorAttributes(request, options);
map.put("status", HttpStatus.BAD_REQUEST.value());
map.put("message", error.getMessage());
return map;
}
}

实现一个


@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler { public GlobalErrorWebExceptionHandler(GlobalErrorAttributes gea, ApplicationContext applicationContext,
ServerCodecConfigurer serverCodecConfigurer) {
super(gea, new WebProperties.Resources(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders());
} //渲染html或json
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
} private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) { final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, ErrorAttributeOptions.defaults()); return ServerResponse.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(errorPropertiesMap));
}
}

方法2, 仅实现一个 ErrorAttributes, 以覆盖默认的 DefaultErrorAttributes


//Spring 默认的就很好了.
@Component
public class GatewayErrorAttributes extends DefaultErrorAttributes { private static final Logger logger = LoggerFactory.getLogger(GatewayErrorAttributes.class); @Override
public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
Throwable error = super.getError(request);
Map<String, Object> errorAttributes = new HashMap<>(8);
errorAttributes.put("message", error.getMessage());
errorAttributes.put("method", request.methodName());
errorAttributes.put("path", request.path()); MergedAnnotation<ResponseStatus> responseStatusAnnotation = MergedAnnotations
.from(error.getClass(), MergedAnnotations.SearchStrategy.TYPE_HIERARCHY).get(ResponseStatus.class); HttpStatus errorStatus = determineHttpStatus(error, responseStatusAnnotation); //必须设置, 否则会报错, 因为 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方法会获取此属性, 重新实现 DefaultErrorWebExceptionHandler也可.
errorAttributes.put("status", errorStatus.value());
errorAttributes.put("code", errorStatus.value()); //html view用
errorAttributes.put("timestamp", new Date());
//html view 用
errorAttributes.put("requestId", request.exchange().getRequest().getId()); errorAttributes.put("error", errorStatus.getReasonPhrase());
errorAttributes.put("exception", error.getClass().getName()); return errorAttributes;
} //从DefaultErrorWebExceptionHandler中复制过来的
private HttpStatus determineHttpStatus(Throwable error, MergedAnnotation<ResponseStatus> responseStatusAnnotation) {
if (error instanceof ResponseStatusException) {
return ((ResponseStatusException) error).getStatus();
}
return responseStatusAnnotation.getValue("code", HttpStatus.class).orElse(HttpStatus.INTERNAL_SERVER_ERROR);
} }

这样就可以了.

注意注意: 必须设置 errorAttributes.put("status", errorStatus.value()) , 否则会报错, 因为 DefaultErrorWebExceptionHandler 的 renderErrorResponse 方法会获取此属性. 除非你自己像方法一一样重新实现 DefaultErrorWebExceptionHandler.

然后在网关中访问一个不存在的服务, 即可看到效果.

curl 'http://127.0.0.1:8900/fundmain22/abc/gogogo?id=1000' --header 'Accept: application/json'
{"exception":"org.springframework.web.server.ResponseStatusException","path":"/fundmain22/abc/gogogo","code":404,"method":"GET","requestId":"094e53e5-1","message":"404 NOT_FOUND","error":"Not Found","status":404,"timestamp":"2021-08-09T11:07:44.106+0000"}

感谢网络上的各种文章...

Spring Cloud Gateway自定义异常处理Exception Handler的更多相关文章

  1. spring cloud gateway自定义过滤器

    在API网关spring cloud gateway和负载均衡框架ribbon实战文章中,主要实现网关与负载均衡等基本功能,详见代码.本节内容将继续围绕此代码展开,主要讲解spring cloud g ...

  2. Spring Cloud Gateway中异常处理

    最近我们的项目在考虑使用Gateway,考虑使用Spring Cloud Gateway,发现网关的异常处理和spring boot 单体应用异常处理还是有很大区别的.让我们来回顾一下异常. 关于异常 ...

  3. Spring Cloud Gateway自定义过滤器实战(观测断路器状态变化)

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  4. Spring Cloud Alibaba学习笔记(21) - Spring Cloud Gateway 自定义全局过滤器

    在前文中,我们介绍了Spring Cloud Gateway内置了一系列的全局过滤器,本文介绍如何自定义全局过滤器. 自定义全局过滤需要实现GlobalFilter 接口,该接口和 GatewayFi ...

  5. Spring Cloud Alibaba学习笔记(19) - Spring Cloud Gateway 自定义过滤器工厂

    在前文中,我们介绍了Spring Cloud Gateway内置了一系列的内置过滤器工厂,若Spring Cloud Gateway内置的过滤器工厂无法满足我们的业务需求,那么此时就需要自定义自己的过 ...

  6. Spring Cloud Alibaba学习笔记(17) - Spring Cloud Gateway 自定义路由谓词工厂

    在前文中,我们介绍了Spring Cloud Gateway内置了一系列的路由谓词工厂,但是如果这些内置的路由谓词工厂不能满足业务需求的话,我们可以自定义路由谓词工厂来实现特定的需求. 例如有某个服务 ...

  7. Spring cloud gateway自定义filter以及负载均衡

    自定义全局filter package com.example.demo; import java.nio.charset.StandardCharsets; import org.apache.co ...

  8. spring cloud gateway 自定义GatewayFilterFactory

    spring cloud gateway提供了很多内置的过滤器,那么因为需求的关系,需要自定义实现,并且要可配置,在一番折腾之后,总算是解决了,那么久记录下来 对于自定义的factory,我们可以选择 ...

  9. 微服务网关实战——Spring Cloud Gateway

    导读 作为Netflix Zuul的替代者,Spring Cloud Gateway是一款非常实用的微服务网关,在Spring Cloud微服务架构体系中发挥非常大的作用.本文对Spring Clou ...

随机推荐

  1. Docker笔记--镜像&基于GO项目创建Docker镜像

    Docker笔记--镜像&基于GO项目创建Docker镜像 核心概念 Doker镜像--包含一个基本的操作系统运行环境和应用程序,镜像是创建Docker容器的基础. Docker容器--如果把 ...

  2. 四、JavaSE语言基础之运算符

    什么是是运算符 运算符:用于数据运算的符号,运算是一种处理.(注:浮点型数据(float.double)进行运算会出现精度丢失的情况) 运算符大致可分为以下六种: 一.算术运算符:+.-.*./.%. ...

  3. POJ 2084 Game of Connections 卡特兰数

    看了下大牛们的,原来这题是卡特兰数,顺便练练java.递归式子:h(0)=1,h(1)=1   h(n)= h(0)*h(n-1) + h(1)*h(n-2) + ... + h(n-1)h(0) ( ...

  4. springBoot-Quartz快速入门

    springBoot-Quartz快速入门 开发环境 JDK1.8.Maven.Idea 技术栈 SpringBoot 2.1.6.quartz 2.3.0等 数据库准备 说明:数据库脚本由Quart ...

  5. 1.6Java语言规范、API、JDK、和IDE

    要点提示:Java语言规范定义了Java的语法,Java库则在JavaAPI中定义.JDK是用于开发和运行Java程序的软件.IDE是快速开发程序的集成开发环境. 计算机语言有严格的使用规范.

  6. 从 Java 代码到 Java 堆

    本文将为您提供 Java 代码内存使用情况的深入见解,包括将 int 值置入一个 Integer 对象的内存开销.对象委托的成本和不同集合类型的内存效率.您将了解到如何确定应用程序中的哪些位置效率低下 ...

  7. 在Xshell中文件内容显示乱码

    1.修改系统语言 支持中文 echo $LANG    查看系统语言  默认 en_US.UFT_8 vim /etc/locale.conf    修改配置文件 将LANG的值改为 zh_CN.UT ...

  8. 使用Gradle构建多模块SpringBoot项目

    使用Gradle构建多模块SpringBoot项目 本项目使用Gradle构建SpringBoot项目,将不同的业务进行不同的模块划分(不做微服务与分布式架构); - 编辑器:Intellij IDE ...

  9. 计算机基础 | 文档神器docsify安装及基本使用

    为啥要用docsify? 神器Docsify让你的文档变得美观,配合typora,从此爱上看文档,各种优点:小巧.快速.美观.方便.快捷.上手快,可以浏览如下优秀案例 ve-charts pyecha ...

  10. centos安装报错:license information (license not accepted)

    前言:在最近部署的centos系统发现个问题 出现报错:安装配置完成后,重启虚拟机出现license  information  (license not accepted) 截图: 解决方案: 在界 ...