首页 > 解决方案 > “消息”字段在错误响应 Spring Boot 中为空

问题描述

我已经处理过这样的未经授权的异常

@ResponseStatus(value= HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends RuntimeException {
    public UnauthorizedException(String message) {
        super(message);
    }
}

但是当我抛出错误如下

throw new UnauthorizedException("Invalid credentials");

我在响应中得到空的错误消息,如下所示

{
    "timestamp": "2020-05-27T13:44:58.032+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "",
    "path": "/auth/register"
}

我尝试使用,

throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid credentials");

但结果还是一样。当我添加spring-boot-devtools依赖项时,我也按预期收到了带有堆栈跟踪的消息。我怎样才能解决这个问题?

春季版本:2.3.0 Java 版本:11.0

标签: javaspringspring-boot

解决方案


好的,他们已将 server.error.include-message 的默认值更改为“never”(请参阅​​此处的评论部分:Spring 2.3.0 Release Info

此处列出了所有默认值: Spring Boot 参考文档

只需像这样配置您的 application.yaml(或属性)。

server:
  error:
    include-message: always
    include-binding-errors: always

请注意,显示错误消息可能会泄露有关您的服务器实现的信息。


推荐阅读