java - 抛出异常时缺少错误响应主体 @Around("@RequestMapping")
问题描述
当我围绕一个用 注释的函数抛出异常时CustomAnnotation
,我得到一个如下所示的响应:
{
"timestamp": "Jan 16, 2019 5:33:08 PM",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/path"
}
但是当我这样做时@annotation(org.springframework.web.bind.annotation.RequestMapping)
,我会收到一个401
没有响应正文的状态。为什么缺少响应正文,我该如何解决这个问题?
这是代码的样子:
@Component
@Aspect
public class AnnotationProcessor {
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
// @Around("@annotation(path.to.my.CustomAnnotation)")
public Object proceed(ProceedingJoinPoint call) throws Throwable {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Unauthorized");
}
}
我的目标是根据为控制器方法指定的注释来验证传入的请求。
如果有人可以提出解决方案/更好的方法来完成同样的事情,那就太好了。
解决方案
我建议使用 ResponseEntity 而不是抛出状态异常
public ResponseEntity<Void> proceed(ProceedingJoinPoint call){
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
您也可以处理该 ResponseEntity 对象上的其他 HttpStatus 。
推荐阅读
- c# - 在视觉 stdio 中安装 Square nuget pacge 时出现问题
- python - Python中的列表:具有特定长度的单词总和
- python - 在 Pandas 中使用 groupby 后如何拆分列中的值?
- tailwind-css - 如何在tailwindcss中实现带有徽章的数据列表
- node.js - 房地产项目在 MongoDB 中存储数据的最佳方式
- google-apps-script - Google表格–当A列中的单元格包含字符串时删除行
- mysql - 如何删除 WITH ROLLUP 获取的不必要值并添加 TOTAL?
- html - 如何使特定元素可滚动,而不是整个页面?
- laravel - laravel 有效载荷在生产中太大
- intershop - 如何解码 BASKET 表上的 COMPUTEDITEMS 字段