/**
* @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之全局异常拦截器的更多相关文章

  1. Spring Cloud Gateway过滤器精确控制异常返回(实战,控制http返回码和message字段)

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 前文<Spring Cloud Gat ...

  2. Spring Cloud Gateway过滤器精确控制异常返回(实战,完全定制返回body)

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 Spring Cloud Gateway应用 ...

  3. Spring Cloud Gateway的全局异常处理

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

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

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

  5. Spring Cloud Gateway过滤器精确控制异常返回(分析篇)

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 在<Spring Cloud Gate ...

  6. Spring Cloud Gateway之全局过滤器在工作中的使用场景

    一.使用注意事项 1.全局过滤器作用于所有的路由,不需要单独配置. 2.通过@Order来指定执行的顺序,数字越小,优先级越高. 二.默认全局拦截器的整体架构 三.实战场景,例如,校验token.记录 ...

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

    一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...

  8. Spring Cloud Gateway GatewayFilter的使用

    Spring Cloud Gateway GatewayFilter的使用 一.GatewayFilter的作用 二.Spring Cloud Gateway内置的 GatewayFilter 1.A ...

  9. 看完就会的Spring Cloud Gateway

    在前面几节,我给大家介绍了当一个系统拆分成微服务后,会产生的问题与解决方案:服务如何发现与管理(Nacos注册中心实战),服务与服务如何通信(Ribbon, Feign实战) 今天我们就来聊一聊另一个 ...

随机推荐

  1. vscode配置c\c++环境

    目录 一.安装vscode 二.安装插件以及配置c\c++编译环境 1. 安装以下两个插件 2. 配置编译环境 一.安装mingw64(推荐) 方法一 方法二 二.如果你安装过visual studi ...

  2. java连接sql server--关于登录验证及对数据库增删改查应用

    一:步骤## 1.sql server建立数据库和相关表 2.建立数据源  (1).打开控制面板找到管理,打开ODBC选项或直接搜索数据源  (2).打开数据源配置后点击添加,选择sql server ...

  3. HTML5新增语法

    ##1.video1.简化版写法:兼容性差```<video src="" controls> </video>``` 2.视频标签标准语法(兼容处理)`` ...

  4. 如何快速创建odoo模块,使用脚手架快速创建自己的odoo应用app

    上一篇内容:如何快速搭建自己的ERP系统,4步源码快速安装odoo教程 了解什么是odoo的插件模块 odoo在基础的框架代码之下,可以安装自己的应用程序或者业务逻辑,也可以对原有的模块进行二次修改 ...

  5. 北航OO第四单元作业总结(4.1~4.3)及课程总结

    前言 在学习过JML规格描述语言之后,本单元进行了UML(Unified Modeling Language)的学习.和JML单纯用语言描述的形式不同,UML通过可视化的图形形式,对一系列有关类的元素 ...

  6. Go-14-解决 go get golang.org/x/text 拉取失败问题

    现象 在执行go get -v github.com/spf13/cobra/cobra 时,报go get golang.org/x/text 拉取失败问题 解决方法: 在 ${gopath}/sr ...

  7. 《鸟哥的Linux私房菜》部分章节学习笔记整理

    简介 此笔记为<鸟哥的Linux私房菜·基础学习篇>中部分章节的学习笔记. 目录 0 计算机概论 1 Linux是什么与如何学习 2 主机规划与磁盘分区 3 安装CentOS7.x 4 首 ...

  8. 记一次 医院.NET公众号系统 线程CPU双高分析

    一:背景 1. 讲故事 上周四有位朋友加wx咨询他的程序出现 CPU + 线程 双高的情况,希望我能帮忙排查下,如下图: 从截图看只是线程爆高,没看到 cpu 爆高哈,有意思的是这位朋友说他: 一直在 ...

  9. 如何高效的遍历Map?你常用的不一定是最快的

    微信公众号:大黄奔跑 关注我,可了解更多有趣的面试相关问题. 写在之前 如文章标题所言,遍历Map是开发过程中比较常见的行为,实现的方式也有多种方式,本文带领大家一起看看更加高效的遍历 Map. 『茴 ...

  10. 用Qt(C++)实现如苹果般的亮屏效果

    用Qt(C++)实现如苹果般的亮屏效果 苹果的亮屏效果可能有很多人没注意到,和其他大部分手机或电脑不同的是,苹果的亮屏特效不是简单的亮度变化,而是一个渐亮的过程.详细来说就是,图片中较亮的部分先显示出 ...