gpt4 book ai didi

spring - Rest Template 自定义异常处理

转载 作者:行者123 更新时间:2023-12-03 12:24:31 24 4
gpt4 key购买 nike

我正在使用来自外部 API 的一些 REST 端点,并且为此目的使用了 Rest Template 接口(interface)。当我从这些调用中收到某些 HTTP 状态代码时,我希望能够引发自定义应用程序异常。为了实现它,我正在实现 ResponseErrorHandler 接口(interface),如下所示:

public class MyCustomResponseErrorHandler implements ResponseErrorHandler {

private ResponseErrorHandler myErrorHandler = new DefaultResponseErrorHandler();

public boolean hasError(ClientHttpResponse response) throws IOException {
return myErrorHandler.hasError(response);
}

public void handleError(ClientHttpResponse response) throws IOException {
String body = IOUtils.toString(response.getBody());
MyCustomException exception = new MyCustomException(response.getStatusCode(), body, body);
throw exception;
}

}

public class MyCustomException extends IOException {

private HttpStatus statusCode;

private String body;

public MyCustomException(String msg) {
super(msg);
// TODO Auto-generated constructor stub
}

public MyCustomException(HttpStatus statusCode, String body, String msg) {
super(msg);
this.statusCode = statusCode;
this.body = body;
}

public HttpStatus getStatusCode() {
return statusCode;
}

public void setStatusCode(HttpStatus statusCode) {
this.statusCode = statusCode;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}

}

最后,这是客户端代码(无关代码省略):
public LoginResponse doLogin(String email, String password) {
HttpEntity<?> requestEntity = new HttpEntity<Object>(crateBasicAuthHeaders(email,password));
try{
ResponseEntity<LoginResponse> responseEntity = restTemplate.exchange(myBaseURL + "/user/account/" + email, HttpMethod.GET, requestEntity, LoginResponse.class);
return responseEntity.getBody();
} catch (Exception e) {
//Custom error handler in action, here we're supposed to receive a MyCustomException
if (e instanceof MyCustomException){
MyCustomException exception = (MyCustomException) e;
logger.info("An error occurred while calling api/user/account API endpoint: " + e.getMessage());
} else {
logger.info("An error occurred while trying to parse Login Response JSON object");
}
}
return null;
}

我的应用上下文:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:spring="http://camel.apache.org/schema/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

<!-- Rest template (used in bridge communication) -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="errorHandler" ref="myCustomResponseErrorHandler"></property>
</bean>

<!-- Bridge service -->
<bean id="myBridgeService" class="a.b.c.d.service.impl.MyBridgeServiceImpl"/>

<!-- Bridge error handler -->
<bean id="myCustomResponseErrorHandler" class="a.b.c.d.service.handlers.MyCustomResponseErrorHandler"/>

</beans>

我怀疑我没有正确理解这种自定义错误处理的行为。每个单独的 rest 模板方法都可能抛出一个 RestClientException,它遵循异常层次结构,是 RuntimeException 的子类,而不是在自定义响应错误处理程序中引发的 IOException,即:I can't catch my custom exception in the rest template method来电。

关于如何捕获这些异常的任何线索? Spring RestTemplate invoking webservice with errors and analyze status code是高度相关的,但从我的角度来看,经历了同样的问题,尽管它是作为解决方案提出的。

[1]:

最佳答案

你已经定制了Exception延伸自 IOException

public class MyCustomException extends IOException {
ResponseErrorHandler#handleError()方法从 RestTemplate#handleResponseError(..) 调用由 RestTemplate#doExecute(..) 调用.此根调用包含在 try-catch 中捕获 IOException 的 block 并重新抛出它包裹在 ResourceAccessException 中,这是一个 RestClientException .

一种可能性是捕获 RestClientException并得到它的 cause .

另一种可能性是使您的自定义 ExceptionRuntimeException 的子类型.

关于spring - Rest Template 自定义异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21429899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com