Rest Template自定义异常处理

贾兰达夫

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

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,它是在自定义响应错误处理程序中抛出的,即:我无法在rest模板方法中捕获我的自定义异常电话。

关于如何捕获这些异常的任何线索?Spring RestTemplate调用有错误的Web服务并分析状态代码是高度相关的,但是从我的角度来看,尽管它是作为解决方案提出的,但我仍然遇到相同的问题。

[1]:

Sotirios Delimanolis

您已将自定义Exception扩展自IOException

public class MyCustomException extends IOException {

ResponseErrorHandler#handleError()方法是从调用RestTemplate#handleResponseError(..)其通过调用RestTemplate#doExecute(..)此根调用被包装在一个try-catch块中,块被捕获IOException并重新包装在a中ResourceAccessException,即a RestClientException

一种可能是抓住RestClientException并获得成功cause

另一种可能性是使您的自定义Exception成为的子类型RuntimeException

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Rest Template自定义异常处理

来自分类Dev

Rest Service中的Spring Boot自定义异常

来自分类Dev

自定义 NotFound 异常 --- Django REST Framework

来自分类Dev

自定义Spring Data Rest @ManyToMany关系处理

来自分类Dev

如何在REST中处理自定义操作?

来自分类Dev

自定义异常处理

来自分类Dev

具有自定义异常类的Spring REST @ResponseStatus不会更改返回状态代码

来自分类Dev

如何在django rest框架中快速抛出带有自定义错误代码的自定义异常并覆盖异常响应中的默认字段

来自分类Dev

Django REST自定义错误

来自分类Dev

WordPress自定义REST API

来自分类Dev

自定义分类WooCommerce Rest API

来自分类Dev

Wp Rest Api自定义终点

来自分类Dev

Keycloak:REST URL自定义端点

来自分类Dev

Django Rest Framework自定义端点

来自分类Dev

自定义字段Django Rest Framework

来自分类Dev

Django Rest Framework的自定义例外

来自分类Dev

Spring REST错误处理:无法获取我的自定义消息

来自分类Dev

Spring 4中的自定义ExceptionTranslationFilter可以处理REST AuthenticationException

来自分类Dev

在Django rest_framework的序列化程序自定义字段中处理无效数据

来自分类Dev

如何在自定义Spring Data Rest控制器中正确处理POST?

来自分类Dev

REST服务的异常处理

来自分类Dev

Rest Api 异常处理

来自分类Dev

处理任务异常-自定义TaskScheduler

来自分类Dev

PLSQL处理自定义异常

来自分类Dev

如何结合使用ServiceStack和自定义REST Api来实现自定义ResponseStatus

来自分类Dev

无法显示来自Wordpress REST API自定义端点的自定义字段

来自分类Dev

在ModelViewSet中的Django-rest自定义URL

来自分类Dev

Django REST框架:读写自定义关系字段

来自分类Dev

Django Rest Framework如何自定义ListAPIView

Related 相关文章

  1. 1

    Rest Template自定义异常处理

  2. 2

    Rest Service中的Spring Boot自定义异常

  3. 3

    自定义 NotFound 异常 --- Django REST Framework

  4. 4

    自定义Spring Data Rest @ManyToMany关系处理

  5. 5

    如何在REST中处理自定义操作?

  6. 6

    自定义异常处理

  7. 7

    具有自定义异常类的Spring REST @ResponseStatus不会更改返回状态代码

  8. 8

    如何在django rest框架中快速抛出带有自定义错误代码的自定义异常并覆盖异常响应中的默认字段

  9. 9

    Django REST自定义错误

  10. 10

    WordPress自定义REST API

  11. 11

    自定义分类WooCommerce Rest API

  12. 12

    Wp Rest Api自定义终点

  13. 13

    Keycloak:REST URL自定义端点

  14. 14

    Django Rest Framework自定义端点

  15. 15

    自定义字段Django Rest Framework

  16. 16

    Django Rest Framework的自定义例外

  17. 17

    Spring REST错误处理:无法获取我的自定义消息

  18. 18

    Spring 4中的自定义ExceptionTranslationFilter可以处理REST AuthenticationException

  19. 19

    在Django rest_framework的序列化程序自定义字段中处理无效数据

  20. 20

    如何在自定义Spring Data Rest控制器中正确处理POST?

  21. 21

    REST服务的异常处理

  22. 22

    Rest Api 异常处理

  23. 23

    处理任务异常-自定义TaskScheduler

  24. 24

    PLSQL处理自定义异常

  25. 25

    如何结合使用ServiceStack和自定义REST Api来实现自定义ResponseStatus

  26. 26

    无法显示来自Wordpress REST API自定义端点的自定义字段

  27. 27

    在ModelViewSet中的Django-rest自定义URL

  28. 28

    Django REST框架:读写自定义关系字段

  29. 29

    Django Rest Framework如何自定义ListAPIView

热门标签

归档