注释为ResponseStatus的自定义异常的动态消息

Vic*_*sky 5 spring spring-mvc

我正在尝试为我的自定义Exception提供动态消息,如下面的代码片段中所示:

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Entity not found")
public class EntityNotFoundException extends RuntimeException {
    public EntityNotFoundException(String msg) {
        super(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

但总是当我抛出它如下所示:

throw new EntityNotFoundException("User entity not found");
Run Code Online (Sandbox Code Playgroud)

在浏览器中,我收到消息"未找到实体"而不是"未找到用户实体".

怎么做到这一点?

小智 9

我坚持这个,但我刚刚删除了@ResponseStatus的原因并且它有效,所以你的代码应该是这样的:

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class EntityNotFoundException extends RuntimeException {
public EntityNotFoundException(String msg) {
    super(msg);
 }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以通过构造函数设置自定义消息