Feign调用全局异常处理解决

本文介绍了一种在使用Feign客户端时遇到的异常处理方法。通过自定义Feign错误解析器,可以将异常信息转化为系统定义的BaseException,并通过全局异常处理类统一返回异常信息给前端。这种方法能够有效解决feign调用服务时的异常处理问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常信息形如:

TestService#addRecord(ParamVO) failed and no fallback available.;

对于failed and no fallback available.这种异常信息,是因为项目开启了熔断:

feign.hystrix.enabled: true
当调用服务时抛出了异常,却没有定义fallback方法,就会抛出上述异常。由此引出了第一个解决方式。

解决方案:

自定义Feign解析器:

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import cn.cicoding.base.jsoncore.exception.BaseException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            // 这里直接拿到我们抛出的异常信息
            String message = Util.toString(response.body().asReader());
            try {
                JSONObject jsonObject = JSONObject.parseObject(message);
                return new BaseException(jsonObject.getString("resultMsg"), jsonObject.getInteger("resultCode"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } catch (IOException ignored) {
        }
        return decode(methodKey, response);
    }
}

定义系统的异常类

public class BaseException extends RuntimeException {
    private int status ;
 
    public int getStatus() {
        return status;
    }
 
    public void setStatus(int status) {
        this.status = status;
    }
 
    public BaseException() {
    }
 
    public BaseException(String message, int status) {
        super(message);
        this.status = status;
    }
 
    public BaseException(String message) {
        super(message);
    }
 
    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }
 
    public BaseException(Throwable cause) {
        super(cause);
    }
 
    public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

统一异常拦截转换对应的异常信息返回前端

public class ResultSet {

    /**
     * 返回的状态码
     */
    private Integer resultCode;

    /**
     * 返回的消息
     */
    private String resultMsg;

    /**
     * 返回的数据
     */
    private Object data;

    public ResultSet() {
    }

    public ResultSet(Integer resultCode, String resultMsg) {
        this.resultCode = resultCode;
        this.resultMsg = resultMsg;
    }

    public ResultSet(Integer resultCode, String resultMsg, Object data) {
        this.resultCode = resultCode;
        this.resultMsg = resultMsg;
        this.data = data;
    }

    public Integer getResultCode() {
        return resultCode;
    }

    public void setResultCode(Integer resultCode) {
        this.resultCode = resultCode;
    }

    public String getResultMsg() {
        return resultMsg;
    }

    public void setResultMsg(String resultMsg) {
        this.resultMsg = resultMsg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

全局异常类处理配置:

@ExceptionHandler(value = BaseException.class)
public ResultSet defaultErrorHandler(HttpServletRequest req, HttpServletResponse resp, BaseException e) {
    ResultSet resultSet = new ResultSet();

    if (e.getStatus() == 400) {
        resultSet.setResultCode(-1);
        resultSet.setResultMsg(e.getMessage());
        resultSet.setData(null);
        resp.setStatus(400);
    } else {
        resp.setStatus(500);
        if(logger.isErrorEnabled()){
            logger.error("系统异常,请联系系统开发人员进行处理", e);
        }
        resultSet.setResultCode(-1);
        resultSet.setResultMsg(e.getMessage());
        resultSet.setData(null);
    }

    return resultSet;
}

这样就能完成了feign接收异常处理的自定义异常信息!

Feign调用服务时,如果遇到异常,通常会抛出`FeignException`或其子类。为了对这类异常进行统一处理,你可以采取以下几种编码策略: 1. **全局异常处理器** (Global Exception Handler): 可以在Feign客户端初始化时设置全局的全局异常处理器,如Spring Cloud Netflix的`ResponseErrorHandler`,它可以捕获并处理所有从Feign调用返回的异常。 ```java feignClient.errorHandler(new ResponseErrorHandler() { @Override public boolean hasError(int code, String reason, IOException e) { // 检查错误代码和原因,返回是否需要处理 } @Override public void handleError(int code, String reason, Exception e) { handleCustomException(e); } }); ``` 2. **拦截器** (Interceptors): 使用Feign的`RequestInterceptor`或`ResponseInterceptor`可以定制每个请求或响应的异常处理逻辑。 ```java feignClient.intercept(new RequestInterceptor() { @Override public void apply(RequestTemplate request) { try { // 添加错误处理代码 } catch (IOException e) { handleCustomException(e); } } }); ``` 3. **自定义Feign Client** (Customized Feign Client): 如果想要更深入地控制异常处理,可以创建一个自定义的`FeignClient`子类,并覆盖其`execute()`方法。 ```java public class CustomFeignClient extends FeignClient { @Override public <T> T target(Class<T> type, String baseUri) { // 在这里添加自定义的异常处理逻辑 } } ``` 4. **使用Java异常处理机制**: 在Feign的回调方法中,可以捕获并处理异常,然后抛出自定义异常或者记录日志。 ```java @FeignClient public interface MyService { @GetMapping("/api") Result callApi(@RequestParam("param") String param) throws MyCustomException; } // 实现类中 try { Result result = myService.callApi(param); } catch (FeignException e) { MyCustomException customEx = new MyCustomException("Error while calling service", e); throw customEx; } ```
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值