繁体   English   中英

限制从Spring Boot Filter返回的响应主体

[英]Restrict the response body that gets returned from Spring Boot Filter

我正在使用spring boot-2.1.6 ,我已经声明了一个过滤器,该过滤器在调用实际到达控制器之前执行基本身份验证操作。 问题是,当我从过滤器中引发异常时(如果未授权调用),它将导致500错误代码,并且整个堆栈跟踪都将打印在响应的正文中。 抛出该异常时,我该如何修改发生的情况或发送什么响应

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

我该如何处理从过滤器引发的错误,以得到有效且对开发人员更友好的响应?

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

@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())));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM