【问题标题】:Feign - handling underling Exceptions - propagating error statusFeign - 处理底层异常 - 传播错误状态
【发布时间】:2017-05-21 11:40:46
【问题描述】:

这是与Netflix Feign - Propagate Status and Exception through Microservices类似的问题

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

这是我的代码:

错误响应解码器:

@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?

【问题讨论】:

    标签: java hystrix feign


    【解决方案1】:

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

    ResponseEntity 很可能会起作用,但我没有尝试使用此解决方案。

    详细设计见:Hystrix - how to register ExceptionMapper

    【讨论】:

      猜你喜欢
      • 2016-12-11
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2018-04-27
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      相关资源
      最近更新 更多