Spring Cloud Gateway之全局异常拦截器
/**
* @version 2019/8/14
* @description: 异常拦截器
* @modified:
*/
@Slf4j
public class JsonExceptionHandler implements ErrorWebExceptionHandler { /**
* MessageReader
*/
private List<HttpMessageReader<?>> messageReaders = Collections.emptyList(); /**
* MessageWriter
*/
private List<HttpMessageWriter<?>> messageWriters = Collections.emptyList(); /**
* ViewResolvers
*/
private List<ViewResolver> viewResolvers = Collections.emptyList(); /**
* 存储处理异常后的信息
*/
private ThreadLocal<ResEntity> exceptionHandlerResult = new ThreadLocal<>(); /**
* 参考AbstractErrorWebExceptionHandler
*/
public void setMessageReaders(List<HttpMessageReader<?>> messageReaders) {
Assert.notNull(messageReaders, "'messageReaders' must not be null");
this.messageReaders = messageReaders;
} /**
* 参考AbstractErrorWebExceptionHandler
*/
public void setViewResolvers(List<ViewResolver> viewResolvers) {
this.viewResolvers = viewResolvers;
} /**
* 参考AbstractErrorWebExceptionHandler
*/
public void setMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
Assert.notNull(messageWriters, "'messageWriters' must not be null");
this.messageWriters = messageWriters;
} @Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
// 按照异常类型进行处理 默认500
int httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
String body = "系统异常,请联系管理员";
if (ex instanceof NotFoundException) {
httpStatus = HttpStatus.NOT_FOUND.value();
body = ex.getMessage();
}else if(ex instanceof ResponseStatusException){
ResponseStatusException responseStatusException = (ResponseStatusException) ex;
httpStatus = responseStatusException.getStatus().value();
body = responseStatusException.getMessage();
} else if (ex instanceof BusinessException) {
body = ex.getMessage();
httpStatus = ((BusinessException) ex).toResEntity().getHttpStatus();
} else if (ex instanceof RuntimeException) {
Throwable cause = ex.getCause();
body = ex.getMessage();
if(null != cause && cause.getMessage().contains("Load balancer does not have available server for client")){
body = "服务不存在";
}
}
//错误记录
ServerHttpRequest request = exchange.getRequest();
log.error("[全局异常处理]异常请求路径:{}", request.getPath());
log.error("异常详细信息:{}",ex);
//封装响应体
ResEntity res = new ResEntity();
res.setHttpStatus(httpStatus);
res.setMsg(body); //参考AbstractErrorWebExceptionHandler
if (exchange.getResponse().isCommitted()) {
return Mono.error(ex);
}
exceptionHandlerResult.set(res);
ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
.switchIfEmpty(Mono.error(ex))
.flatMap((handler) -> handler.handle(newRequest))
.flatMap((response) -> write(exchange, response)); } /**
* 参考DefaultErrorWebExceptionHandler
*/
protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
ResEntity result = exceptionHandlerResult.get(); //404 因前端框架问题,不转换处理 ,因此目前只有系统报500才转换为自定义的状态码
if(HttpStatus.INTERNAL_SERVER_ERROR.value() == result.getHttpStatus()){
return ServerResponse.status(HttpStatus.OK.value())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(result));
}
return ServerResponse.status(result.getHttpStatus())
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(result));
} /**
* 参考AbstractErrorWebExceptionHandler
*/
private Mono<? extends Void> write(ServerWebExchange exchange,
ServerResponse response) {
exchange.getResponse().getHeaders()
.setContentType(response.headers().getContentType());
return response.writeTo(exchange, new ResponseContext());
} /**
* 参考AbstractErrorWebExceptionHandler
*/
private class ResponseContext implements ServerResponse.Context { @Override
public List<HttpMessageWriter<?>> messageWriters() {
return JsonExceptionHandler.this.messageWriters;
} @Override
public List<ViewResolver> viewResolvers() {
return JsonExceptionHandler.this.viewResolvers;
}
}
}
Spring Cloud Gateway之全局异常拦截器的更多相关文章
- Spring Cloud Gateway过滤器精确控制异常返回(实战,控制http返回码和message字段)
欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 前文<Spring Cloud Gat ...
- Spring Cloud Gateway过滤器精确控制异常返回(实战,完全定制返回body)
欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 Spring Cloud Gateway应用 ...
- Spring Cloud Gateway的全局异常处理
Spring Cloud Gateway中的全局异常处理不能直接用@ControllerAdvice来处理,通过跟踪异常信息的抛出,找到对应的源码,自定义一些处理逻辑来符合业务的需求. 网关都是给接口 ...
- Spring Cloud Alibaba学习笔记(21) - Spring Cloud Gateway 自定义全局过滤器
在前文中,我们介绍了Spring Cloud Gateway内置了一系列的全局过滤器,本文介绍如何自定义全局过滤器. 自定义全局过滤需要实现GlobalFilter 接口,该接口和 GatewayFi ...
- Spring Cloud Gateway过滤器精确控制异常返回(分析篇)
欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 在<Spring Cloud Gate ...
- Spring Cloud Gateway之全局过滤器在工作中的使用场景
一.使用注意事项 1.全局过滤器作用于所有的路由,不需要单独配置. 2.通过@Order来指定执行的顺序,数字越小,优先级越高. 二.默认全局拦截器的整体架构 三.实战场景,例如,校验token.记录 ...
- 【Spring Cloud & Alibaba 实战 | 总结篇】Spring Cloud Gateway + Spring Security OAuth2 + JWT 实现微服务统一认证授权和鉴权
一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...
- Spring Cloud Gateway GatewayFilter的使用
Spring Cloud Gateway GatewayFilter的使用 一.GatewayFilter的作用 二.Spring Cloud Gateway内置的 GatewayFilter 1.A ...
- 看完就会的Spring Cloud Gateway
在前面几节,我给大家介绍了当一个系统拆分成微服务后,会产生的问题与解决方案:服务如何发现与管理(Nacos注册中心实战),服务与服务如何通信(Ribbon, Feign实战) 今天我们就来聊一聊另一个 ...
随机推荐
- c++ 反汇编 构造函数和析构函数
构造函数和析构函数出现的时机 局部对象 109: // 局部对象定义调用构造函数 110: 111: CNumber Number; 00C8A37D 8D 4D EC lea ecx,[Number ...
- Pytorch数据读取与预处理实现与探索
在炼丹时,数据的读取与预处理是关键一步.不同的模型所需要的数据以及预处理方式各不相同,如果每个轮子都我们自己写的话,是很浪费时间和精力的.Pytorch帮我们实现了方便的数据读取与预处理方法,下面记录 ...
- 通过xshell实现内网linux上公网yum、apt-get安装软件
环境:在内网,我的机器可上网,内网服务器不可上网,本来在我机器上开个代理,服务器直接通过我机器上网就可以,奈何网络配置太复杂,目前只有ssh端口可通. 先安装ccproxy软件,配置http监听端口为 ...
- Linux 服务器性能测试报告-sysbench命令实践
Linux 服务器性能测试报告 我们使用linux 工具sysbench 来测试linux服务器性能,目前在Centos上进行操作 Install sysbench yum -y install sy ...
- 学习笔记-ionic3 环境配置搭建到打包
折腾了两周总算理清楚了,参考的链接如下: https://blog.csdn.net/zeternityyt/article/details/79655150 环境配置 https://segmen ...
- redis的主从复制(哨兵模式)
p.p1 { margin: 0; font: 10px ".SF NS Text" } Master以写为主,Slave以读为主 读写分离 容灾恢复 一.一主多从 配置文件修改: ...
- 带你全面认识CMMI V2.0(终)——实施落地
引入CMMI的方法 一共有四个阶段将您的业务过程和最佳实践最终融合在一起,并在该范围内重新创造整个组织的"完成方式".这四个阶段是: 战略探索:此阶段的重点是了解当前状态并计划过渡 ...
- 如何快速搭建自己的ERP系统,4步源码快速安装odoo教程
上一篇内容:了解什么是Odoo,为二次开发做准备 1.下载odoo源码 Github地址:https://github.com/odoo/odoo Gitee地址:https://gitee.com/ ...
- ISP算法:深入聊聊lens shading
一.简介 关于什么是成像中的lens shading这里直接引用一句英文的definition:"The term shading describes the light fall-off ...
- python中的数据结构-链表
一.什么是链表 链表是由一系列节点构成,每个节点由一个值域和指针域构成,值域中存储着用户数据,指针域中存储这指向下一个节点的指针.根据结构的不同,链表可以分为单向链表.单向循环链表.双向链表.双向循环 ...