Feign调用接口,获取异常信息自定义异常。

在Feign调用接口时,如果遇到异常,可以通过自定义ErrorDecoder来获取异常信息并抛出自定义异常。以下是具体的步骤和代码示例:

  1. 定义自定义异常:首先,你需要定义一个自定义异常类,用于封装异常信息。
public class CustomException extends RuntimeException {
    private String errorCode;
    private String message;

    public CustomException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
        this.message = message;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public String getMessage() {
        return message;
    }
}
  1. 实现Feign的ErrorDecoder接口:创建一个类实现ErrorDecoder接口,并在decode方法中解析异常信息,提取errorCode,并抛出自定义异常。
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CustomErrorDecoder implements ErrorDecoder {
    private final ErrorDecoder defaultErrorDecoder = new Default();

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            String json = Util.toString(response.body().asReader());
            ObjectMapper mapper = new ObjectMapper();
            JsonNode errorNode = mapper.readTree(json).path("error");
            if (errorNode.isMissingNode()) {
                return defaultErrorDecoder.decode(methodKey, response);
            }
            String errorCode = errorNode.path("errorCode").asText();
            String message = errorNode.path("message").asText();
            return new CustomException(errorCode, message);
        } catch (IOException e) {
            return defaultErrorDecoder.decode(methodKey, response);
        }
    }
}
  1. 配置Feign客户端使用自定义ErrorDecoder:在你的Feign客户端配置中指定使用自定义的ErrorDecoder
import org.springframework.context.annotation.Bean;

public class FeignConfig {
    @Bean
    public ErrorDecoder errorDecoder() {
        return new CustomErrorDecoder();
    }
}
  1. 使用Feign客户端:在你的服务中使用Feign客户端,并处理可能抛出的自定义异常。
@FeignClient(name = "auditApplicationApi", configuration = FeignConfig.class)
public interface AuditApplicationApi {
    @PostMapping("/audit-applications")
    String create(CreateAuditApplicationDto dto);
}

public class AuditApplicationService {
    public void createAuditApplication(CreateAuditApplicationDto dto) {
        try {
            AuditApplicationApi api = Feign.builder().target(AuditApplicationApi.class);
            api.create(dto);
        } catch (CustomException e) {
            // 处理自定义异常
            System.out.println("Error code: " + e.getErrorCode());
            System.out.println("Error message: " + e.getMessage());
            throw e;
        }
    }
}

通过上述步骤,你可以在Feign调用接口时捕获异常信息,并根据异常信息抛出自定义异常。这样就可以在调用方获取到服务端抛出的自定义错误码,并进行相应的异常处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值