Interface DownstreamErrorMapper

Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface public interface DownstreamErrorMapper

將已知下游錯誤契約轉譯為應用程式安全例外的擴充點。

mapper 只應在下游 status、錯誤碼與 payload schema 都通過明確 allowlist 時回傳例外; 例外訊息與 violations 必須由應用重新組裝,不得直接使用未驗證的下游 message、路徑、 stack trace 或完整 response body。回傳 empty、回傳 null 或 mapper 執行失敗時, StandardHttpClient 會回到帶 DownstreamHttpFailure 的不透明預設處理。

使用範例

client.setDownstreamErrorMapper((failure, response, parser) -> {
    if (failure.statusCode() != 409) {
        return Optional.empty();
    }
    InventoryError payload = parser.read(response, InventoryError.class);
    if (!"ITEM_RESERVED".equals(payload.code())) {
        return Optional.empty();
    }
    return Optional.of(new ConflictException("The item is no longer available."));
});
See Also:
  • Method Details

    • map

      Optional<ApplicationException> map(DownstreamHttpFailure failure, org.apache.hc.core5.http.ClassicHttpResponse response, HttpResponseParser parser)

      嘗試把下游錯誤轉譯為應用程式公開契約的一部分。

      response entity 是一次性串流;mapper 可透過 parser 讀取一次。無論是否完成轉譯, 該次 HTTP 呼叫都會以例外結束,因此 fallback 不會再次讀取 entity。

      Parameters:
      failure - 已去除 query string 的下游診斷脈絡
      response - 原始下游錯誤回應
      parser - 框架 HTTP response parser
      Returns:
      已驗證並重新組裝的應用程式例外;不處理時為 empty