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

时间:2019-07-08 04:44:29

标签: java spring-boot spring-cloud

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

我尝试了spring boot-2.1.6,但是我很快发现它基本上是用于调用到达控制器然后引发异常的。对于过滤器,它是行不通的。

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

1 个答案:

答案 0 :(得分:1)

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

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