Java 后端 / 知识点

Spring Cloud 微服务速查手册

手册条目

将远程服务的状态码和错误响应转换为统一异常模型。

统一调用错误

当 Feign 调用返回非 2xx 状态时,在客户端边界读取远程错误体,转换为统一异常,再由全局异常处理器输出稳定的错误结构。这样业务代码无需分别处理 400、404、500 或各服务自定义 JSON。Spring Cloud OpenFeign 会从应用上下文或指定的 Feign 配置中查找 ErrorDecoder Bean。:contentReference[oaicite:0]{index=0}

转换链路

远程调用错误统一转换链路

统一模型至少保留内部错误码、可展示消息、上游状态码和链路 ID。上游原始响应只用于受控日志,不应直接返回给外部调用方。

基本实现

下面是 Spring Boot 3、Java 17 的片段示例,依赖 spring-cloud-starter-openfeign。该配置注册为全局 ErrorDecoder;只想作用于单个客户端时,将配置类放入对应 @FeignClient(configuration = RemoteErrorConfig.class),并避免被全局组件扫描。

java
package com.example.remote;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.charset.StandardCharsets;

@Configuration
class RemoteErrorConfig {

    private static final int MAX_ERROR_BODY_BYTES = 16 * 1024;

    @Bean
    ErrorDecoder errorDecoder(ObjectMapper mapper) {
        return (methodKey, response) -> {
            String body = readBody(response);
            String upstreamCode = "UNKNOWN";
            String message = "远程服务调用失败";
            String traceId = firstHeader(response, "X-Trace-Id");

            // 只读取约定字段;解析失败时返回通用消息,避免泄露原始响应。
            try {
                JsonNode node = mapper.readTree(body);
                upstreamCode = node.path("code").asText(upstreamCode);
                message = node.path("message").asText(message);
                traceId = node.path("traceId").asText(traceId);
            } catch (Exception ignored) {
                message = "远程服务返回不可解析错误";
            }

            return new RemoteCallException(
                    methodKey, response.status(), upstreamCode, message, traceId);
        };
    }

    private static String readBody(Response response) {
        if (response.body() == null) {
            return "";
        }
        try (var input = response.body().asInputStream()) {
            return new String(input.readNBytes(MAX_ERROR_BODY_BYTES), StandardCharsets.UTF_8);
        } catch (Exception ignored) {
            return "";
        }
    }

    private static String firstHeader(Response response, String name) {
        return response.headers().entrySet().stream()
                .filter(entry -> entry.getKey().equalsIgnoreCase(name))
                .flatMap(entry -> entry.getValue().stream())
                .findFirst()
                .orElse(null);
    }
}

record ApiError(
        String code,
        String message,
        int upstreamStatus,
        String upstreamCode,
        String traceId) {
}

final class RemoteCallException extends RuntimeException {
    private final String methodKey;
    private final int upstreamStatus;
    private final String upstreamCode;
    private final String traceId;

    RemoteCallException(
            String methodKey,
            int upstreamStatus,
            String upstreamCode,
            String message,
            String traceId) {
        super(message);
        this.methodKey = methodKey;
        this.upstreamStatus = upstreamStatus;
        this.upstreamCode = upstreamCode;
        this.traceId = traceId;
    }

    String methodKey() {
        return methodKey;
    }

    int upstreamStatus() {
        return upstreamStatus;
    }

    String upstreamCode() {
        return upstreamCode;
    }

    String traceId() {
        return traceId;
    }
}

@RestControllerAdvice
class RemoteCallExceptionHandler {

    @ExceptionHandler(RemoteCallException.class)
    ResponseEntity<ApiError> handle(RemoteCallException exception) {
        ApiError body = new ApiError(
                "REMOTE_CALL_FAILED",
                exception.getMessage(),
                exception.upstreamStatus(),
                exception.upstreamCode(),
                exception.traceId());

        // 对外统一为 502;是否映射业务型 4xx,应由显式规则决定。
        return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(body);
    }
}

假设上游返回:

text
HTTP/1.1 404 Not Found
X-Trace-Id: trace-7f2
Content-Type: application/json

{"code":"ORDER_NOT_FOUND","message":"订单不存在","traceId":"trace-7f2"}

预期结果:

text
HTTP/1.1 502 Bad Gateway
Content-Type: application/json

{"code":"REMOTE_CALL_FAILED","message":"订单不存在","upstreamStatus":404,"upstreamCode":"ORDER_NOT_FOUND","traceId":"trace-7f2"}

读取时先看 code 判断本系统异常类型,再看 upstreamStatus 与 upstreamCode 定位远程服务语义,最后使用 traceId 串联双方日志。methodKey 只用于内部日志定位 Feign 接口,不应直接返回给外部调用方。

风险与边界

不要把所有上游 4xx 原样透传。触发条件是远程服务错误码语义与当前 API 不一致,后果是调用方依赖错误的状态码或暴露内部资源信息;安全替代方案是维护明确映射表,未命中的状态统一返回 502。

不要直接返回原始响应体。触发条件是上游包含堆栈、SQL、账号或内部地址,后果是敏感信息泄露;替代方案是只提取白名单字段,并限制日志长度、脱敏后记录。

读取响应体后不能再次读取同一流。若后续组件仍需原始体,应在解码器内一次性缓存并显式传递,否则会出现空体或二次读取失败。

排障清单

  • 未进入 ErrorDecoder:确认异常确实来自 Feign 非 2xx 响应,并检查该 Bean 是否被目标客户端配置加载。
  • 错误体始终为空:检查网关或上游是否已消费、压缩或替换响应体,并确认字符集。
  • traceId 丢失:统一约定响应头名称,并在网关、客户端和服务端全链路透传。
  • 业务 404 被统一成 502:为可信且稳定的业务错误建立显式映射,不要按状态码范围批量透传。

目录与阅读设置

记录一个想法

Spring Cloud 微服务速查手册

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通