Spring Cloud Gateway中异常处理
最近我们的项目在考虑使用Gateway,考虑使用Spring Cloud Gateway,发现网关的异常处理和spring boot 单体应用异常处理还是有很大区别的。让我们来回顾一下异常。
关于异常是拿来干什么的,很多人老程序员认为就是拿来我们Debug的时候排错的,当然这一点确实是异常机制非常大的一个好处,但异常机制包含着更多的意义。
- 关注业务实现。异常机制使得业务代码与异常处理代码可以分开,你可以将一些你调用数据库操作的代码写在一个方法里而只需要在方法上加上throw DB相关的异常。至于如何处理它,你可以在调用该方法的时候处理或者甚至选择不处理,而不是直接在该方法内部添加上if判断如果数据库操作错误该如何办,这样业务代码会非常混乱。
- 统一异常处理。与上一点有所联系。我当前所在项目的实践是,自定义业务类异常,在Controller或Service中抛出,让后使用Spring提供的异常接口统一处理我们自己在内部抛出的异常。这样一个异常处理架构就非常明了。
- 程序的健壮性。如果没有异常机制,那么来了个对空对象的某方法调用怎么办呢?直接让程序挂掉?这令人无法接受,当然,我们自己平时写的一些小的东西确实是这样,没有处理它,让后程序挂了。但在web框架中,可以利用异常处理机制捕获该异常并将错误信息传递给我们然后继续处理下个请求。所以异常对于健壮性是非常有帮助的。
异常处理(又称为错误处理)功能提供了处理程序运行时出现的任何意外或异常情况的方法。异常处理使用 try、catch 和 finally 关键字来尝试可能未成功的操作,处理失败,以及在事后清理资源。异常根据意义成三种:业务、系统、代码异常,不同的异常采用不同的处理方式。具体的什么样的异常怎么处理就不说了。
红线和绿线代表两条异常路径
1,红线代表:请求到Gateway发生异常,可能由于后端app在启动或者是没启动
2,绿线代表:请求到Gateway转发到后端app,后端app发生异常,然后Gateway转发后端异常到前端
红线肯定是走Gateway自定义异常:
两个类的代码如下(参考:http://cxytiandi.com/blog/detail/20548):
@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;
}
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);
} /**
* 获取异常属性
*/
@Override
protected 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));
} /**
* 指定响应处理方法为JSON处理的方法
* @param errorAttributes
*/
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
} /**
* 根据code获取对应的HttpStatus
* @param errorAttributes
*/
@Override
protected 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);
logger.error(map.toString());
return map;
}
}
绿线代表Gateway转发异常
转发的异常,肯定是springboot单体中处理的,至于spring单体中的异常是怎么处理的呢?肯定是用@ControllerAdvice去做。
@ExceptionHandler(value = Exception.class)
@ResponseBody
public AppResponse exceptionHandler(HttpServletRequest request, Exception e) {
String ip = RequestUtil.getIpAddress(request);
logger.info("调用者IP:" + ip);
String errorMessage = String.format("Url:[%s]%n{%s}", request.getRequestURL().toString(), e.getMessage());
logger.error(errorMessage, e);
return AppResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
}
到这里基本上可以了,大家不要试着去用Gateway去捕获后端异常,回到最初的起点,API 网关(API Gateway)主要负责服务请求路由、组合及协议转换,异常同样也是一样,Gateway只负责转发单体应用的异常,不要试图Gateway捕获后端服务异常,然后再输出给前端。感谢猿天地的一句惊醒梦中人!
Spring Cloud Gateway中异常处理的更多相关文章
- Spring Cloud Gateway自定义异常处理Exception Handler
版本: Spring Cloud 2020.0.3 常见的方法有 实现自己的 DefaultErrorWebExceptionHandler 或 仅实现ErrorAttributes. 方法1: Er ...
- Spring Cloud Gateway的全局异常处理
Spring Cloud Gateway中的全局异常处理不能直接用@ControllerAdvice来处理,通过跟踪异常信息的抛出,找到对应的源码,自定义一些处理逻辑来符合业务的需求. 网关都是给接口 ...
- Spring Cloud Gateway 没有链路信息,我 TM 人傻了(中)
本系列是 我TM人傻了 系列第五期[捂脸],往期精彩回顾: 升级到Spring 5.3.x之后,GC次数急剧增加,我TM人傻了 这个大表走索引字段查询的 SQL 怎么就成全扫描了,我TM人傻了 获取异 ...
- 看完就会的Spring Cloud Gateway
在前面几节,我给大家介绍了当一个系统拆分成微服务后,会产生的问题与解决方案:服务如何发现与管理(Nacos注册中心实战),服务与服务如何通信(Ribbon, Feign实战) 今天我们就来聊一聊另一个 ...
- Spring Cloud Gateway夺命连环10问?
大家好,我是不才陈某~ 最近有很多小伙伴私信我催更 <Spring Cloud 进阶>,陈某也总结了一下,最终原因就是陈某之前力求一篇文章将一个组件重要知识点讲透,这样导致了文章篇幅很长, ...
- Spring Cloud Gateway过滤器精确控制异常返回(实战,完全定制返回body)
欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 Spring Cloud Gateway应用 ...
- Spring Cloud Gateway服务网关
原文:https://www.cnblogs.com/ityouknow/p/10141740.html Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gatewa ...
- spring cloud gateway之filter篇
转载请标明出处: https://www.fangzhipeng.com 本文出自方志朋的博客 在上一篇文章详细的介绍了Gateway的Predict,Predict决定了请求由哪一个路由处理,在路由 ...
- 网关服务Spring Cloud Gateway(一)
Spring 官方最终还是按捺不住推出了自己的网关组件:Spring Cloud Gateway ,相比之前我们使用的 Zuul(1.x) 它有哪些优势呢?Zuul(1.x) 基于 Servlet,使 ...
随机推荐
- Html与CSS学习书单
1.Head First HTML与CSS(第二版) 豆瓣详情 这本书非常适合入门学习HTML与CSS它的内容不一定详实,但一定是你入门的首选.作为一本引进 图书翻译尚可.目前豆瓣评分9.3.
- 使用Mobile Device Manager Plus mdm软件进行完备的移动设备管理
使用Mobile Device Manager Plus mdm软件进行完备的移动设备管理 什么是移动设备管理(mdm管理系统)? 移动设备管理(mdm管理系统)旨在管理企业内移动设备.管理员使用md ...
- 小白的CTF学习之路6——阶段测评
刚才考了自己一次,下面我把题和答案放到下面 CPU中不含有以下选项中的 C A: 运算器 B: 寄存器 C: 内存 D: 时钟 这是一道送分题,CPU包含以下几种原 ...
- java操作FTP的一些工具方法
java操作FTP还是很方便的,有多种开源支持,这里在apache开源的基础上自己进行了一些设计,使用起来更顺手和快捷. 思路: 1.设计FTPHandler接口,可以对ftp,sftp进行统一操作, ...
- spring 5.1.2 mvc RequestMappingHandlerMapping 源码初始化过程
RequestMappingHandlerMapping getMappingForMethod RequestMappingHandlerMapping 继承于 AbstractHandlerMet ...
- 自定义react-navigation的TabBar
在某些情况下,默认的react-navigation的tab bar无法满足开发者的要求.这个时候就需要自定义一个tab bar了.本文就基于react-navigtion v2来演示如何实现一个自定 ...
- python对象的for迭代实现
第一种:__iter__ 实现__iter__的对象,是可迭代对象.__iter__方法可以直接封装一个迭代器,从而实现for循环 class A: def __init__(self): self. ...
- 进军微信小程序之准备工作
小程序这么火,不去浪一浪怎么行? 更何况,现在微信“赦免”了个人认证,又更新了web开发工具,现在正是搞搞小程序的最佳时期! 那么一起来看看要做什么准备吧~ 官方的文档很详细,可参考:小程序官 ...
- quartus 一种管脚分配方法
第一步: 在QII软件中,使用“Assignments -> Remove Assignments”标签,移除管脚分配内容,以确保此次操作,分配的管脚没有因为覆盖而出现错误的情况. 编写xxx. ...
- cvpr2018(转发一篇头条)
CVPR 2018:腾讯图像去模糊.自动人像操纵最新研究 新智元 2018-05-29 14:13:04 新智元报道 来源:腾讯优图 编辑:江磊.克雷格 [新智元导读]即将在6月美国盐湖城举行的计算机 ...