java - Feign - 处理底层异常 - 传播错误状态

标签 java hystrix feign

这与 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?

最佳答案

首先 - 我不需要后备机制。

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

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

关于java - Feign - 处理底层异常 - 传播错误状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510282/

相关文章:

java - Hystrix 请求缓存示例

java - Spring Cloud Hystrix 在第一次命令调用时失败

spring-cloud-feign - 如何使用 Feign Error Decoder 消除流关闭错误?

spring-cloud-feign - feign如何获取所请求接口(interface)的头数据

java - 如何加载外部java类并调用带参数的方法

java - 无法清楚理解java中的运行时监听器

java - 拆分字节数组以映射 java 类对象中的字段的有效方法

java - 库更改后主机名与对等方提供的证书主题不匹配

spring-boot - 假装下载文件

java - Android:在不同的Android版本中上传图片时出错