【问题标题】:How to get HTTP status in advice recovery callback如何在建议恢复回调中获取 HTTP 状态
【发布时间】:2021-11-18 15:39:16
【问题描述】:

我有一个简单的集成流程,它通过多次尝试向外部资源发送请求。我为此目的创建RequestHandlerRetryAdvice

RequestHandlerRetryAdvice requestHandlerRetryAdvice = new RequestHandlerRetryAdvice();
requestHandlerRetryAdvice.setRecoveryCallback(retryContext -> {
    Message<?> failedMessage = ((MessagingException) retryContext.getLastThrowable()).getFailedMessage();
    //TODO: get http status
    return failedMessage.getPayload();
});

我需要知道的是 http 状态。我怎样才能得到它?

【问题讨论】:

    标签: java spring-integration


    【解决方案1】:

    HTTP 状态是抛出异常的一部分:

    ((MessagingException) retryContext.getLastThrowable()).getCause() 应该包含一个带有getStatusCode() 属性的HttpStatusCodeException

    我的测试表明:

    retryContext = ...
     lastException = org.springframework.messaging.MessagingException: ...
      failedMessage = ...
      backtrace = {Object[6]@7673} 
      detailMessage = "Failed to handle"
      cause = org.springframework.messaging.MessageHandlingException: ...
       failedMessage = ...
       cause = {HttpClientErrorException$Forbidden@7685} "org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden: [no body]"
        statusCode = {HttpStatus@7690} "403 FORBIDDEN"
        rawStatusCode = 403
        statusText = "Forbidden"
    

    代码是这样的:

    .handle(Http.outboundGateway("/service/internal?{params}")
                                    .uriVariable("params", "payload")
                                    .expectedResponseType(String.class),
                            e ->  e.advice(retryAdvice()))
    
    private RequestHandlerRetryAdvice retryAdvice() {
            RequestHandlerRetryAdvice requestHandlerRetryAdvice = new RequestHandlerRetryAdvice();
            requestHandlerRetryAdvice.setRecoveryCallback(retryContext -> {
                MessagingException lastThrowable = (MessagingException) retryContext.getLastThrowable();
                return ((HttpStatusCodeException) lastThrowable.getCause().getCause()).getStatusCode();
            });
            return requestHandlerRetryAdvice;
        }
    

    【讨论】:

    • 在我的例子中是MessageHandlingException
    • .getCause().getCause() 那么呢?
    • 不幸的是,任何级别都没有HttpStatusCodeException
    • 请在我的回答中查看编辑。你确定你真的在谈论你的代码中的 HTTP 调用吗?
    • 好的,这对我有用。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2017-05-13
    相关资源
    最近更新 更多