SpringCloud feign服务熔断下的异常处理操作
作者:Coder_Joker 发布时间:2022-01-11 20:22:45
今天做项目的时候,遇到一个问题,如果我调用某个服务的接口,但是这个服务挂了,同时业务要求这个接口的结果是必须的,那我该怎么办呢,答案是通过hystrix,但是又有一点,服务不是平白无故挂的(排除服务器停电等问题),也就是说有可能是timeout or wrong argument 等等,那么我该如何越过hystrix的同时又能将异常成功抛出呢
第一点:先总结一下异常处理的方式:
1):通过在controller中编写@ExceptionHandler 方法
直接在controller中编写异常处理器方法
@RequestMapping("/test")
public ModelAndView test()
{
throw new TmallBaseException();
}
@ExceptionHandler(TmallBaseException.class)
public ModelAndView handleBaseException()
{
return new ModelAndView("error");
}
但是呢这种方法只能在这个controller中有效,如果其他的controller也抛出了这个异常,是不会执行的
2):全局异常处理:
@ControllerAdvice
public class AdminExceptionHandler
{
@ExceptionHandler(TmallBaseException.class)
public ModelAndView hAndView(Exception exception)
{
//logic
return null;
}
}
本质是aop代理,如名字所言,全局异常处理,可以处理任意方法抛出的异常
3)通过实现SpringMVC的HandlerExceptionResolver接口
public static class Tt implements HandlerExceptionResolver
{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex)
{
//logic
return null;
}
}
然后在mvc配置中添加即可
@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
//初始化异常处理器链
exceptionResolvers.add(new Tt());
}
}
接下来就是Fegin ,如果想自定义异常需要了解1个接口:ErrorDecoder
先来看下rmi调用结束后是如果进行decode的
Object executeAndDecode(RequestTemplate template) throws Throwable {
Request request = targetRequest(template);
//代码省略
try {
if (logLevel != Logger.Level.NONE) {
response =
logger.logAndRebufferResponse(metadata.configKey(), logLevel, response, elapsedTime);
response.toBuilder().request(request).build();
}
if (Response.class == metadata.returnType()) {
if (response.body() == null) {
return response;
}
if (response.body().length() == null ||
response.body().length() > MAX_RESPONSE_BUFFER_SIZE) {
shouldClose = false;
return response;
}
// Ensure the response body is disconnected
byte[] bodyData = Util.toByteArray(response.body().asInputStream());
return response.toBuilder().body(bodyData).build();
}
//从此处可以发现,如果状态码不再200-300,或是404的时候,意味着非正常响应就会对内部异常进行解析
if (response.status() >= 200 && response.status() < 300) {
if (void.class == metadata.returnType()) {
return null;
} else {
return decode(response);
}
} else if (decode404 && response.status() == 404 && void.class != metadata.returnType()) {
return decode(response);
} else {
throw errorDecoder.decode(metadata.configKey(), response);
}
} catch (IOException e) {
if (logLevel != Logger.Level.NONE) {
logger.logIOException(metadata.configKey(), logLevel, e, elapsedTime);
}
throw errorReading(request, response, e);
} finally {
if (shouldClose) {
ensureClosed(response.body());
}
}
}
默认的解析方式是:
public static class Default implements ErrorDecoder {
private final RetryAfterDecoder retryAfterDecoder = new RetryAfterDecoder();
@Override
public Exception decode(String methodKey, Response response) {
//获取错误状态码,生成fegin自定义的exception
FeignException exception = errorStatus(methodKey, response);
Date retryAfter = retryAfterDecoder.apply(firstOrNull(response.headers(), RETRY_AFTER));
if (retryAfter != null) {
//如果重试多次失败,则抛出相应的exception
return new RetryableException(exception.getMessage(), exception, retryAfter);
}
//否则抛出默认的exception
return exception;
}
我们可以发现,做了2件事,第一获取状态码,第二重新抛出异常,额外的判断是否存在多次失败依然error的异常,并没有封装太多的异常,既然如此那我们就可以封装我们自定义的异常了
但是注意,这块并没有涉及hystrix,也就意味着对异常进行处理还是会触发熔断机制,具体避免方法最后讲
首先我们编写一个BaseException 用于扩展:省略getter/setter
public class TmallBaseException extends RuntimeException
{
/**
*
* @author joker
* @date 创建时间:2018年8月18日 下午4:46:54
*/
private static final long serialVersionUID = -5076254306303975358L;
// 未认证
public static final int UNAUTHENTICATED_EXCEPTION = 0;
// 未授权
public static final int FORBIDDEN_EXCEPTION = 1;
// 超时
public static final int TIMEOUT_EXCEPTION = 2;
// 业务逻辑异常
public static final int BIZ_EXCEPTION = 3;
// 未知异常->系统异常
public static final int UNKNOWN_EXCEPTION = 4;
// 异常码
private int code;
// 异常信息
private String message;
public TmallBaseException(int code, String message)
{
super(message);
this.code = code;
this.message = message;
}
public TmallBaseException(String message, Throwable cause)
{
super(message, cause);
this.message = message;
}
public TmallBaseException(int code, String message, Throwable cause)
{
super(message, cause);
this.code = code;
this.message = message;
}
}
OK,我们定义好了基类之后可以先进行测试一番:服务接口controller:
//显示某个商家合作的店铺
@RequestMapping(value="/store")
public ResultDTO<Collection<BrandDTO>>findStoreOperatedBrands(@RequestParam("storeId")Long storeId)
{
为了测试,先直接抛出异常
throw new TmallBaseException(TmallBaseException.BIZ_EXCEPTION, "ceshi");
}
接口:
@RequestMapping(value="/auth/brand/store",method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
ResultDTO<List<BrandDTO>>findStoreOperatedBrands(@RequestParam("storeId")Long storeId);
其余的先不贴了,然后我们发起rest调用的时候发现,抛出异常之后并没有被异常处理器处理,这是因为我们是通过fegin,而我又配置了feign的fallback类,抛出异常的时候会自动调用这个类中的方法.
有两种解决方法:
1.直接撤除hystrix ,很明显its not a good idea
2.再封装一层异常类,具体为何,如下
AbstractCommand#handleFallback 函数是处理异常的函数,从方法后缀名可以得知,当exception 是HystrixBadRequestException的时候是直接抛出的,不会触发fallback,也就意味着不会触发降级
final Func1<Throwable, Observable<R>> handleFallback = new Func1<Throwable, Observable<R>>() {
@Override
public Observable<R> call(Throwable t) {
circuitBreaker.markNonSuccess();
Exception e = getExceptionFromThrowable(t);
executionResult = executionResult.setExecutionException(e);
if (e instanceof RejectedExecutionException) {
return handleThreadPoolRejectionViaFallback(e);
} else if (t instanceof HystrixTimeoutException) {
return handleTimeoutViaFallback();
} else if (t instanceof HystrixBadRequestException) {
return handleBadRequestByEmittingError(e);
} else {
/*
* Treat HystrixBadRequestException from ExecutionHook like a plain HystrixBadRequestException.
*/
if (e instanceof HystrixBadRequestException) {
eventNotifier.markEvent(HystrixEventType.BAD_REQUEST, commandKey);
return Observable.error(e);
}
return handleFailureViaFallback(e);
}
}
};
既然如此,那一切都明了了,修改类的继承结构即可:
public class TmallBaseException extends HystrixBadRequestException
{
/**
*
* @author joker
* @date 创建时间:2018年8月18日 下午4:46:54
*/
private static final long serialVersionUID = -5076254306303975358L;
// 未认证
public static final int UNAUTHENTICATED_EXCEPTION = 0;
// 未授权
public static final int FORBIDDEN_EXCEPTION = 1;
// 超时
public static final int TIMEOUT_EXCEPTION = 2;
// 业务逻辑异常
public static final int BIZ_EXCEPTION = 3;
// 未知异常->系统异常
public static final int UNKNOWN_EXCEPTION = 4;
// 异常码
private int code;
// 异常信息
private String message;
}
至于怎么从服务器中获取异常然后进行转换,就是通过上面所讲的ErrorHandler:
public class TmallErrorDecoder implements ErrorDecoder
{
@Override
public Exception decode(String methodKey, Response response)
{
System.out.println(methodKey);
Exception exception=null;
try
{
String json = Util.toString(response.body().asReader());
exception=JsonUtils.json2Object(json,TmallBaseException.class);
} catch (IOException e)
{
e.printStackTrace();
}
return exception!=null?exception:new TmallBaseException(TmallBaseException.UNKNOWN_EXCEPTION, "系统运行异常");
}
}
最后微服务下的全局异常处理就ok了,当然这个ErrorDdecoder 和BaseException推荐放在common模块下,所有其它模块都会使用到它。
来源:https://blog.csdn.net/Coder_Joker/article/details/81811567


猜你喜欢
- 老生常谈的配置 但是还是需要说明一下EurekaApplication @EnableEurekaServer指定为server端
- 同时使用and和or的查询UserServiceImpl 类,service实现类import org.springframework.be
- java异常分为两大类,Checked异常和Runtime异常,Checked异常都是在编译阶段可以被处理的异常。Checked异常和Run
- 1、问题引入我们已经完成了后台系统的登录功能开发,但是目前还存在一个问题,就是用户如果不登录,直接访问系统首页面,照样可以正常访问。很明显,
- 1.两种取值方式的差异mapper.xml映射文件<select id="selectEmployeeByCondition
- 下面通过代码给大家介绍c++ string insert() 函数,具体内容如下:basic_string& inser
- 首先,良好的编码规范非常重要。在 java 程序中,访问速度、资源紧张等问题的大部分原因,都是代码不规范造成的。单例的使用场景单例模式对于减
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&
- android中提供了4中动画: AlphaAnimation 透明度动画效果 ScaleAnimation 缩放动画效果 Translat
- 使用过 mybatis 框架的小伙伴们都知道,mybatis 是个半 orm 框架,通过写 mapper 接口就能自动实现数据库的增删改查,
- 这篇文章主要从以下几个方面来介绍。简单介绍下jersey,springboot,重点介绍如何整合springboot与jersey。什么是j
- 本文实例讲述了C#判断一天、一年已经过了百分之多少的方法。分享给大家供大家参考。具体如下:这里写了四个函数,分别是1.判断当前时间过了今天的
- 目录一、新建简单窗口二、编写窗口中的按键三、简单的按键运行1.流布局管理器:2.静态文本框:四、窗口画图五、窗口鼠标响应六、总结好了,sto
- 题目:将一个数组逆序输出。代码:import java.util.*;public class lianxi31 {public stati
- 1.一段java程序是如何运行起来的呢?Java源文件,通过编译器,产生.Class字节码文件,字节码文件通过Java虚拟机中的解释器,编译
- Intellij IDEA 配置Subversion插件实现步骤详解在使用Intellij的过程中,突然发现svn不起效了,在VCS–》Ch
- 在value目录下,创建styles.xml文件<?xml version="1.0" encoding=&quo
- Java 表格数据导入word文档中个人觉得这个功能实在搞笑,没什么意义,没办法提了需求就要实现,(太好说话了把我)我的实现是再word中生
- 本文实例为大家分享了Android中TabLayout结合ViewPager实现页面切换,供大家参考,具体内容如下一、实现思路1、在buil
- CAS 的基本概念CAS(Compare-and-Swap)是一种多线程并发编程中常用的原子操作,用于实现多线程间的同步和互斥访问。 它操作