首页 > 解决方案 > 限制从 Spring Boot Filter 返回的响应体

问题描述

我正在使用spring boot-2.1.6,我已经声明了一个过滤器,它在调用实际到达控制器之前执行基本身份验证操作。问题是当我从过滤器中抛出异常时(如果调用未经授权),它会导致 500 错误代码和整个堆栈跟踪被打印在响应正文中。我怎样才能修改发生的事情,或者更确切地说,当抛出该异常时要发送什么响应

我试过@ControllerAdvice了,但我很快发现它基本上是为了当调用到达控制器然后引发异常时。对于过滤器,它不起作用。

如何将过滤器抛出的错误处理为有效且对开发人员更友好的响应?

标签: javaspring-bootspring-cloud

解决方案


您可以捕获该异常并在过滤器中作为错误响应抛出。

@Component
public class AuthenticationFilter implements Filter {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        try {
            if(basicAuthenticationFails) { // Your Authentication Logic
                throw new UnAuthorizedException("Error while processing");
            }
            chain.doFilter(request, response);
        } catch (UnAuthorizedException e) { // Create a custom exception for this.
            ((HttpServletResponse) response).sendError(HttpStatus.UNAUTHORIZED.value(), "UnAuthorized);
        }
    }
}

这将返回一个如下所示的 json,

{
   "timestamp":"2019-07-08T05:47:34.870+0000",
   "status":401,
   "error":"Unauthorized",
   "message":"UnAuthorized",
   "path":"/foo"
}

您也可以通过创建一个class,

try {
// Logic
} catch (UnAuthorizedException e) {
   ((HttpServletResponse) response).setStatus(HttpStatus.BAD_GATEWAY.value());
   response.getWriter().write(objectMapper.writeValueAsString(new ErrorResponse(e.getMessage())));
}

推荐阅读