Cloud中feign异常无法传递的问题

重写feign 全局异常处理方法:

分析: 

 因为 cloud内部抛出异常不进行处理,Feign获取spring默认包装异常结果如下:

 

{
 "timestamp": "2017-12-27 15:01:53",
  "status": 500,
  "error": "Internal Server Error",
  "exception": "com.keruyun.loyalty.commons.master.exception.BusinessException",
  "message": "Request processing failed; nested exception is {\"code\":1000, \"message\":\"test Exception\"}",
  "path": "/coupon/cloud/commercial/8469"
  }

  可以自定义 

ExceptionInfo  如果没有此类的话:

 

@Data
public class ExceptionInfo {
    private Long timestamp;

    private Integer status;

    private String exception;

    private String message;

    private String path;

    private String error;
}

异常处理类如下:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import jdk.nashorn.internal.runtime.regexp.joni.exception.InternalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

*/
/**
 * @Description
 * 解决Spring Cloud中feign异常无法传递的问题,跨链路调用client端异常无法正确捕获
 * 高版本的cloud 可能不存在此问题
 * @create 2019-04-24 13:37
 **//*

@Configuration
public class ExceptionErrorDecoder implements ErrorDecoder {

    Logger log = LoggerFactory.getLogger(
        ExceptionErrorDecoder.class);

    @Override
    public Exception decode(String var1, Response response) {

        try {
            if (response.body() != null) {
                String body = Util.toString(response.body().asReader());
                log.error(body);
                ExceptionInfo exceptionInfo = JSON.parseObject(body, new TypeReference<ExceptionInfo>() {
                    });
                Class clazz = Class.forName(exceptionInfo.getException());
                return (Exception) clazz.getDeclaredConstructor(String.class)
                    .newInstance(exceptionInfo.getMessage());
            }
        } catch (Exception var4) {
            log.error(var4.getMessage());
            return new InternalException(var4.getMessage());
        }
        return new InternalException("系统异常,请联系管理员");
    }
}

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值