【问题标题】:How to get Response code and Response body , When a filter is invoked and throws exception in spring boot如何获取响应代码和响应正文,当调用过滤器并在 Spring Boot 中引发异常时
【发布时间】:2018-12-27 18:58:35
【问题描述】:
I am using Swagger to get response of PUT() method. I have created a filter to limit request body size to 10000kb in my Spring boot Application. When I send request os size greater than 10000kb, i get swagger response as below.
Response Body :"no content" 
Response code: 500

我参考了下面的链接 Spring boot Embedded Tomcat "application/json" post request restriction to 10KB

我用下面来注册过滤器..

@Bean
    public FilterRegistrationBean loginRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new ApplicationJsonRequestSizeLimitFilter());
        filterRegistrationBean.setUrlPatterns(Collections.singletonList("/*"));
        return filterRegistrationBean;
}

如何在响应正文中获取状态代码和过滤器抛出的自定义消息。

【问题讨论】:

    标签: java rest spring-boot swagger-ui spring-filter


    【解决方案1】:

    你应该试试@ControllerAdvice

    这是一个示例。

    @ControllerAdvice
    public class GlobalExceptionResolver{
    
    @ResponseStatus(HttpStatus.BAD_REQUEST, reason = "Invalid request type")
    @ExceptionHandler(value = SomeException.class)
    public ResponseEntity<CustomError> handleSomeException(HttpServletRequest request, SomeException e){
        CustomError error = new CustomError();
        error.setMessage("Very large file");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
    }
    }
    

    【讨论】:

    • 能否详细解释一下,比如我们如何在这里获取请求对象,以及如何注册这个
    • 您可以简单地将请求作为参数传递。
    • 这里有更好的解释如何使用它。 dzone.com/articles/…
    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 2017-06-09
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多