为什么handleresponse(uri url,httpmethod方法,clienthttpresponse响应)resttemplate的方法。

发布于 2025-02-09 06:35:07 字数 2409 浏览 3 评论 0 原文

我正在使用 RESTTEMPLATE 从我的代码中调用外部API 如下:

       try {

            responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                    UploadResonse.class);
        } catch (BusinessException ex) {
            fetchErrorResponseEntity = ex.getResponseEntity();
            if (fetchErrorResponseEntity.getStatusCodeValue() == 404) {
                throw new BusinessException(ex.getMessage(), ErrorResponse.NOT_FOUND);
            } else if (fetchErrorResponseEntity.getStatusCodeValue() == 500) {
                throw new BusinessException(ex.getMessage(),
                                          ErrorResponse.INTERNAL_SERVER_ERROR);
            } else if (fetchErrorResponseEntity.getStatusCodeValue() == 400) {
                throw new BusinessException(ex.getMessage(), ErrorResponse.INVALID_REQUEST);
            }

        }

此API呼叫返回 200 Success ,但是当我调试它时,它仍然会转到 handleresponse( URI URL,httpmethod方法,clienthttpresponse响应) restTemplate.class.class 的方法

,然后它来了我的restTemplateErrorhandler.java文件,

    @Override
public boolean hasError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    return clientHttpResponse.getStatusCode() != HttpStatus.OK;
}

@Override
public void handleError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    String errMessage = getErrMessage(clientHttpResponse);
    HttpStatus status = clientHttpResponse.getStatusCode();
    switch (status) {
    case BAD_REQUEST: // 400
        throw new BusinessException(errMessage,
                ErrorResponse.INVALID_REQUEST);
    case NOT_FOUND:
      throw new BusinessException(errMessage, ErrorResponse.NOT_FOUND);
    case SERVICE_UNAVAILABLE: // 503
        throw new BusinessException(errMessage, ErrorResponse.TIME_OUT);
    case METHOD_NOT_ALLOWED: // 405
    case INTERNAL_SERVER_ERROR: // 500
    default:
        throw new BusinessException(errMessage,
                ErrorResponse.INTERNAL_SERVER_ERROR);
    }
}

有人可以帮助我租赁是否有正确的行为。 我怀疑,如果响应是 200成功,它不应转到 restTemlate.class restTemplateTemplateErrorhandler.Class 当API返回 201创建状态时,此行为正在造成问题,该时间到了 handle error()方法并返回默认情况 internal_server_error 有人可以在这里帮我吗

I am calling an external API from my code using RestTemplate like below:

       try {

            responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
                    UploadResonse.class);
        } catch (BusinessException ex) {
            fetchErrorResponseEntity = ex.getResponseEntity();
            if (fetchErrorResponseEntity.getStatusCodeValue() == 404) {
                throw new BusinessException(ex.getMessage(), ErrorResponse.NOT_FOUND);
            } else if (fetchErrorResponseEntity.getStatusCodeValue() == 500) {
                throw new BusinessException(ex.getMessage(),
                                          ErrorResponse.INTERNAL_SERVER_ERROR);
            } else if (fetchErrorResponseEntity.getStatusCodeValue() == 400) {
                throw new BusinessException(ex.getMessage(), ErrorResponse.INVALID_REQUEST);
            }

        }

This API call is returning 200 Success but when I debug it, it still goes to handleResponse(URI url, HttpMethod method, ClientHttpResponse response) method of RestTemplate.class

And then it's coming to my RestTemplateErrorHandler.java file

    @Override
public boolean hasError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    return clientHttpResponse.getStatusCode() != HttpStatus.OK;
}

@Override
public void handleError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    String errMessage = getErrMessage(clientHttpResponse);
    HttpStatus status = clientHttpResponse.getStatusCode();
    switch (status) {
    case BAD_REQUEST: // 400
        throw new BusinessException(errMessage,
                ErrorResponse.INVALID_REQUEST);
    case NOT_FOUND:
      throw new BusinessException(errMessage, ErrorResponse.NOT_FOUND);
    case SERVICE_UNAVAILABLE: // 503
        throw new BusinessException(errMessage, ErrorResponse.TIME_OUT);
    case METHOD_NOT_ALLOWED: // 405
    case INTERNAL_SERVER_ERROR: // 500
    default:
        throw new BusinessException(errMessage,
                ErrorResponse.INTERNAL_SERVER_ERROR);
    }
}

Can someone lease help me to understand if it's the correct behaviour.
I suspect that if the response is 200 Success it should not go to the RestTemlate.class and RestTemplateErrorHandler.class
This behaviour is creating problem when API return 201 Created status, that time it goes to handleError() method and return the default case INTERNAL_SERVER_ERROR
Can someone please help me here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

◇流星雨 2025-02-16 06:35:07

以下代码每次响应不是 200 ok ,如果成功 201创建,则会调用错误处理程序。

@Override
public boolean hasError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    return clientHttpResponse.getStatusCode() != HttpStatus.OK;
}

尝试将实现更改为以下内容:

@Override
public boolean hasError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    return !clientHttpResponse.getStatusCode().is2xxSuccessful();
}

这更适合您的需求,因为它将将所有 2xx 状态视为成功的请求,而不是仅 200 OK ok

The following code will call the error handler every time the response is not 200 OK, event if it is successful like 201 Created.

@Override
public boolean hasError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    return clientHttpResponse.getStatusCode() != HttpStatus.OK;
}

Try changing the implementation to the following:

@Override
public boolean hasError(ClientHttpResponse clientHttpResponse)
        throws IOException {
    return !clientHttpResponse.getStatusCode().is2xxSuccessful();
}

This is better suited for your needs as it will consider all 2xx status as successful requests instead of only 200 OK.

白日梦 2025-02-16 06:35:07

根据 ResponseerRorhandler (如果需要),该接口是RESTTEMPLATE使用的接口来确定特定响应是否有错误。
RESTTEMPLATEERHANDLER class实施 ResponseerRorhandler

如果 haserror()方法返回 true ,那么Spring将自动调用 handleRor()方法。这是流。

如果您检查 handleresponse 方法的实现,以下给出,您会发现有一个调用 HaserRor 方法来检查响应是否有任何错误。 Haserror 方法的默认实现将返回true是响应代码是 4xx 5xx 。如果没有错误,则方法将继续执行,并且不会调用handleror方法,如我上面所述。

protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        ResponseErrorHandler errorHandler = this.getErrorHandler();
        boolean hasError = errorHandler.hasError(response);
        if (this.logger.isDebugEnabled()) {
            try {
                this.logger.debug(method.name() + " request for \"" + url + "\" resulted in " + response.getRawStatusCode() + " (" + response.getStatusText() + ")" + (hasError ? "; invoking error handler" : ""));
            } catch (IOException var7) {
                ;
            }
        }
        if (hasError) {
            errorHandler.handleError(url, method, response);
        }

    }

在代码中,您发布的 HaserRor 将返回 true 对于所有不同 200 的响应代码。这就是为什么调用 handleror

According to documentation method handleResponse() as it name suggests will handle the given response, perform appropriate logging and invoke the ResponseErrorHandler (if needed) which is interface used by the RestTemplate to determine whether a particular response has an error or not.
RestTemplateErrorHandler class implements implements ResponseErrorHandler.

If the hasError() method returns true then Spring will automatically call the handleError() method. This is the flow.

If you check implementation for handleResponse method, given below, you will see that there is a call to hasError method to check if the response has any errors. Default implementation of hasError method will return true is response code is 4XX or 5XX. If there is no errors, method will proceed execution and handleError method won't be invoked, as I explained above.

protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        ResponseErrorHandler errorHandler = this.getErrorHandler();
        boolean hasError = errorHandler.hasError(response);
        if (this.logger.isDebugEnabled()) {
            try {
                this.logger.debug(method.name() + " request for \"" + url + "\" resulted in " + response.getRawStatusCode() + " (" + response.getStatusText() + ")" + (hasError ? "; invoking error handler" : ""));
            } catch (IOException var7) {
                ;
            }
        }
        if (hasError) {
            errorHandler.handleError(url, method, response);
        }

    }

In code you posted hasError will return true for all response codes that are different from 200. That's why handleError is invoked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文