java - 限制从 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())));
}
推荐阅读
- database - Oracle 11g,orapwd.exe 打不开
- python - 在范围函数 Python 中使用自定义顺序
- python - python脚本中的ListRecommendationsRequest构造函数错误
- reactjs - 如何在不重新渲染站点或使用 MuiThemeProvider 的情况下更改材质 ui 元素的颜色
- python - 如何在 Firebase 中按降序排列数据 - Python
- python - 构造类类型的枚举值
- python - 递归查找列表的所有组合
- ajax - 如何在 onunload 函数中向我的服务器发送同步 ajax 请求
- c++ - 为什么 c++ DLL 中的多线程在构建时会出现错误 C3867?
- python - 有没有办法在 Django 中合并 2 个查询集并按它们的相关字段对它们进行排序?