Feign客户端错误处理

4

我正在使用Feign客户端,

我有一个位置服务。因此,我使用FeignClient为我的LocationService创建了一个客户端。

@FeignClient(url="http://localhost:9003/location/v1", name="location-service")
public interface LocationControllerVOneClient {

    @RequestMapping(value = "/getMultipleLocalities", method = RequestMethod.POST)
    public Response<Map<Integer, Locality>> getMultipleLocalities(List<Integer> localityIds);

    @RequestMapping(value = "/getMultipleCities", method = RequestMethod.POST)
    public Response<Map<Integer, City>> getMultipleCities(List<Integer> cityIds);

    @RequestMapping(value = "/getMultipleStates", method = RequestMethod.POST)
    public Response<Map<Integer, State>> getMultipleStates(List<Integer> stateIds);

    @RequestMapping(value = "/getMultipleCitiesName", method = RequestMethod.POST)
    public Response<Map<Integer, String>> getMultipleCitiesName(MultiValueMap<String, String> formParams);

    @RequestMapping(value = "/getMultipleStatesName", method = RequestMethod.POST)
    public Response<Map<Integer, String>> getMultipleStatesName(MultiValueMap<String, String> formParams);

    @RequestMapping(value = "/getMultipleLocalitiesName", method = RequestMethod.POST)
    public Response<Map<Integer, String>> getMultipleLocalitiesName(MultiValueMap<String, String> formParams);

}

现在其他服务可能会通过LocationClient调用这个LocationService。
我希望在一个公共的地方为这个Feign Client(LocationClient)进行异常处理(即,我不想让每个调用者都这样做。这应该是LocationClient的一部分)。 异常可能是连接被拒绝(如果LocationService宕机),超时等。
2个回答

2
您可以使用Feign的ErrorDecoder来处理异常。以下是相关的URL供您参考。 https://github.com/OpenFeign/feign/wiki/Custom-error-handling 示例:
public class MyErrorDecoder implements ErrorDecoder {

    private final ErrorDecoder defaultErrorDecoder = new Default();

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() >= 400 && response.status() <= 499) {
            return new MyBadRequestException();
        }
        return defaultErrorDecoder.decode(methodKey, response);
    }

}

要获取这个ErrorDecoder,您需要按照以下方式创建它的bean:
@Bean
public MyErrorDecoder myErrorDecoder() {
  return new MyErrorDecoder();
}

豆子的名称应该如何命名?根据名称,谁将获得这个豆子?我只看到使用openfeign的方法,而不是Spring的Feign客户端作为bean。 - WesternGun

1
您可以定义一个回退客户端,当出现诸如超时或连接被拒绝的异常时调用它:
@FeignClient(url="http://localhost:9003/location/v1", name="location-service", fallback=LocationFallbackClient.class)
public interface LocationControllerVOneClient {
    ...
}

LocationFallbackClient 必须实现 LocationControllerVOneClient


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接