You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RequestHandlerRetryAdvice的恢复回调中获取HTTP状态码

实现方法

你调用HTTP出站组件请求失败时,抛出的HTTP状态相关异常会被包装在MessagingException的异常链路中,你只需要解包异常找到对应类型即可拿到状态码,示例代码如下:

import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.messaging.MessagingException;

RequestHandlerRetryAdvice requestHandlerRetryAdvice = new RequestHandlerRetryAdvice();
requestHandlerRetryAdvice.setRecoveryCallback(retryContext -> {
    Throwable lastThrowable = retryContext.getLastThrowable();
    Integer httpStatusCode = null;

    // 遍历异常链路查找HTTP状态异常
    Throwable currentEx = lastThrowable;
    while (currentEx != null) {
        if (currentEx instanceof HttpStatusCodeException httpEx) {
            // Spring 6+ 用下面的写法
            httpStatusCode = httpEx.getStatusCode().value();
            // Spring 5及更低版本可以用 httpEx.getRawStatusCode()
            break;
        }
        currentEx = currentEx.getCause();
    }

    Message<?> failedMessage = ((MessagingException) lastThrowable).getFailedMessage();
    // 此处可使用获取到的httpStatusCode做自定义逻辑
    // 注意:如果是连接超时、DNS解析失败等根本没收到服务端响应的场景,httpStatusCode会为null,需要自行做兼容处理
    return failedMessage.getPayload();
});

内容的提问来源于stack exchange,提问作者bartex9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 17:06:02