【问题标题】:How to pass and handle Exceptions through HTTP responses in Spring?Spring中如何通过HTTP响应传递和处理异常?
【发布时间】:2020-04-20 14:52:27
【问题描述】:

我的 Spring 项目中有一个客户端和服务器模块在不同的端口上运行。客户端模块通过 RestTemplate 向服务器发出 POST 请求。服务器模块抛出带有自定义错误消息的自定义异常。目前,在我的项目中,服务器有一个 RestControllerAdvice 类来处理如下异常:

@RestControllerAdvice
public class AppRestControllerAdvice {
    @ExceptionHandler(ApiException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public MessageData handle(ApiException e) {
        MessageData data = new MessageData();
        data.setMessage(e.getMessage());
        return data;
    }
}

在客户端,以下方法捕获来自服务器的响应。

@RestControllerAdvice
public class AppRestControllerAdvice {
    @ExceptionHandler(ApiException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public MessageData handle(ApiException e) {
        MessageData data = new MessageData();
        data.setMessage(e.getMessage());
        return data;
    }

    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public MessageData handle(Throwable e) {
        MessageData data = new MessageData();
        data.setMessage("UNKNOWN ERROR- " + e.getMessage());
        e.printStackTrace();
        return data;
    }
}

每当在服务器上抛出异常时,这是我在客户端上收到的内容

{
  "message": "UNKNOWN ERROR- org.springframework.web.client.HttpClientErrorException: 400 Bad Request"
}

我的问题是,我如何检索源自服务器的自定义异常消息

另外,为什么客户端正确的 RestControllerAdvice 模块没有发现错误? (INTERNAL_SERVER_ERROR 方法而不是 BAD_REQUEST 方法捕获错误。)

【问题讨论】:

    标签: spring exception resttemplate


    【解决方案1】:

    我的问题是,如何检索源自服务器的自定义异常消息?

    要检索原始异常消息,您必须使用能够提取该信息的专用ResponseErrorHandler,而不是使用默认的(DefaultResponseErrorHandler - 我假设您使用它是因为您收到的消息 - @987654323 @)。

    创建:

    public class CustomerResponseErrorHandler extends DefaultResponseErrorHandler {
    
        @Override
        public void handleError(ClientHttpResponse httpResponse) throws IOException {
    
            // here you have access to the response's body which potentially contains the exception message you are interested in  
            // simply extract it if possible and throw an exception with that message
            // in other case you can simply call `super.handlerError()` - do whatever suits you
    
        }
    }
    

    然后将它与您的RestTemplate 一起使用:

    @Configuration
    public class RestTemplateConfig {
    
        @Bean
        public RestTemplate restTemplate(RestTemplateBuilder builder) {
            return builder
              .errorHandler(new CustomerResponseErrorHandler())
              .build();
        }
    
    }
    

    另外,为什么客户端上正确的 RestControllerAdvice 模块没有发现错误? (INTERNAL_SERVER_ERROR 方法而不是 BAD_REQUEST 方法捕获错误。)

    正确的方法被执行了——你的RestTemplate此刻正在抛出HttpClientErrorException,这不是ApiException。不过是Throwable

    【讨论】:

    • 基本上需要事先了解异常,以便将异常映射/解析到您的自定义异常处理程序。
    猜你喜欢
    • 2018-09-13
    • 2014-09-07
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2018-04-12
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多