Feign - 处理underling异常 - 传播错误状态

时间:2017-01-06 16:45:54

标签: java hystrix feign

这与Netflix Feign - Propagate Status and Exception through Microservices

类似

我有假装和hystrix的微服务架构。 我的问题是当underling服务返回错误响应时 - 比如状态404 - 我的FallbackFactory应该传播它,但它总是返回200

这是我的代码:

ErrorResponseDecoder:

@Component
public class ErrorResponseDecoder implements ErrorDecoder {

private ErrorDecoder delegate = new ErrorDecoder.Default();

@Override
public Exception decode(String methodKey, Response response) {
    HttpHeaders responseHeaders = new HttpHeaders();
    for(Map.Entry<String,Collection<String>> entry : response.headers().entrySet()) {
        responseHeaders.put(entry.getKey(), new ArrayList<>(entry.getValue()));
    }
    HttpStatus statusCode = HttpStatus.valueOf(response.status());
    String statusText = response.reason();

    byte[] responseBody;
    try {
        responseBody = IOUtils.toByteArray(response.body().asInputStream());
    } catch (IOException e) {
        throw new RuntimeException("Failed to process response body.", e);
    }

    if (response.status() >= 400 && response.status() <= 499) {
        return new HttpClientErrorException(statusCode, statusText, responseHeaders, responseBody, null);
    }

    if (response.status() >= 500 && response.status() <= 599) {
        return new HttpServerErrorException(statusCode, statusText, responseHeaders, responseBody, null);
    }
    return delegate.decode(methodKey, response);
}
}

后备:

@Component
public class ServiceFallbackFactory implements FallbackFactory<ServiceFeign> {

@Override
public ServiceFeign create(final Throwable cause) {

    return new ServiceFeign() {

        @Override
        public Response getList(String date) {
            if(cause instanceof HttpStatusCodeException) {
                HttpStatusCodeException exc = (HttpStatusCodeException)cause;
                return Response.status(exc.getStatusCode().value()).entity(exc.getMessage()).build();
            } else {
                throw new RuntimeException(cause);
            }
        }
    }
}

输出:

{
  "statusType": "NOT_FOUND",
  "entity": "404 Not Found",
  "entityType": "java.lang.String",
  "metadata": {},
  "status": 404
}

Http状态:200 :( 我怎样才能把它变成404?

1 个答案:

答案 0 :(得分:0)

首先 - 我不需要回退机制。

最有可能 select * from table_name where (name = @name or @name = '') and (surname = @surname or @surname = '') and (gender = @gender or @gender = '') 可行,但我没有尝试使用此解决方案。

有关详细设计,请参阅:Hystrix - how to register ExceptionMapper