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("系統異常,請聯繫管理員");
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章