如何获取响应代码和响应主体,在Spring Boot中调用过滤器并引发异常时

时间:2018-07-19 15:04:12

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

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;
}

如何获取状态码以及由响应主体中的过滤器引发的自定义消息。

1 个答案:

答案 0 :(得分:0)

您应该尝试@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);
}
}