【问题标题】:Restrict the response body that gets returned from Spring Boot Filter限制从 Spring Boot Filter 返回的响应体
【发布时间】:2019-07-08 04:44:29
【问题描述】:
我正在使用spring boot-2.1.6,我已经声明了一个过滤器,它在调用实际到达控制器之前执行基本身份验证操作。问题是当我从过滤器中抛出异常时(如果调用未经授权),它会导致 500 错误代码和整个堆栈跟踪被打印在响应正文中。我如何修改发生的情况,或者更确切地说,当抛出该异常时要发送什么响应
我尝试了@ControllerAdvice,但我很快发现它基本上是用于当调用到达控制器然后引发异常时。而对于过滤器,它就不起作用了。
如何将过滤器抛出的错误处理为有效且对开发人员更友好的响应?
【问题讨论】:
标签:
java
spring-boot
spring-cloud
【解决方案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())));
}