首页 > 解决方案 > 抛出异常时缺少错误响应主体 @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");
    }
}

我的目标是根据为控制器方法指定的注释来验证传入的请求。

如果有人可以提出解决方案/更好的方法来完成同样的事情,那就太好了。

标签: javaspringaspectj

解决方案


我建议使用 ResponseEntity 而不是抛出状态异常

public ResponseEntity<Void> proceed(ProceedingJoinPoint call){
    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}

您也可以处理该 ResponseEntity 对象上的其他 HttpStatus 。


推荐阅读