假设客户端错误处理

时间:2017-10-10 08:42:47

标签: spring-boot spring-cloud-feign

我正在使用Feign Client,

我有位置服务。所以我使用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 个答案:

答案 0 :(得分:0)

您可以定义在超时或连接拒绝等异常出现时调用的回退客户端:

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

LocationFallbackClient必须实施LocationControllerVOneClient

答案 1 :(得分:0)

您可以使用伪装的ErrorDecoder进行异常处理。以下是供您参考的网址。

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();
}