1. 起因
使用feign有个很头疼的事情,自定义异常在下游服务会被feignException拦截,返回的格式会非常奇怪,feign本身还有熔断机制,各种处理方法侵入性都太强
找不到太好的解决方案,就费时间自己优化了下,demo如下
算是目前我的最优解决方案
2. demo
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import os.common.utils.constants.Constants;
import os.common.utils.resp.ApiResult;
import os.common.utils.resp.MyException;
import java.util.List;
@Slf4j
@RestControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(FeignException.class)
public ApiResult handleException(FeignException e){
ApiResult resp = new ApiResult();
resp.setCode(e.status());
String[] result = StringUtils.substringsBetween(e.getLocalizedMessage(),"nested exception is ","\",");
if(null != result && result.length > Constants.ONE){
String[] myException = StringUtils.split(result[Constants.ZERO],": ");
resp.setMessage(result[Constants.ZERO]);
if(myException.length > Constants.ZERO){
resp.setMessage(myException[Constants.ONE]);
}
log.error(result[Constants.ZERO],e);
return resp;
}
resp.setMessage(e.getMessage());
log.error(e.getMessage());
return resp;
}
}
3. 后话
上面Constants.ONE之类的是常量类,对应相应的数字,ZERO = 0 ONE = 1
其实也就是用全局异常处理拦截FeignException异常,然后暴力截取字符串,性能上考虑用了lang3的StringUtils的工具类,速度上还行,另外说回来,系统天天异常,那就该考虑下是不是系统代码有问题了。
另外,关于全局异常和统一返回信息,请参考我之前的博客,或者根据自己项目修改
https://blog.csdn.net/soulsda/article/details/83684445
总之,解决方案核心还是拦截 + 截取字符串