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() {
                    });
                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("系统异常,请联系管理员");
    }
}

 

 

你可能感兴趣的:(springboot,springCloud)