java - Spring ResponseStatusException 不返回原因

标签 java spring-boot rest error-handling

我有一个非常简单的 @RestController ,我正在尝试设置自定义错误消息。但由于某种原因,message因为错误没有出现。
这是我的 Controller :

@RestController
@RequestMapping("openPharmacy")
public class OpenPharmacyController {


    @PostMapping
    public String findNumberOfSurgeries(@RequestBody String skuLockRequest) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "This postcode is not valid");
    }

}
这是我得到的回应:
{
    "timestamp": "2020-06-24T17:44:20.194+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/openPharmacy/"
}
我正在传递一个 JSON,但我没有验证任何东西,我只是想设置自定义消息。如果我更改状态代码,我会在响应中看到,但 message总是空的。
为什么这不像预期的那样工作?这是一个如此简单的例子,我看不出可能遗漏了什么。当我调试代码时,我可以看到错误消息设置了所有字段。但出于某种原因,该消息从未在响应中设置。

最佳答案

此答案由用户 Hassan 在对原始问题的评论中提供。我只是将其发布为答案,以提高可见度。
基本上,您需要做的就是添加 server.error.include-message=always到您的 application.properties 文件,现在您的消息字段应该被填充。
此行为在 Spring Boot 2.3 中已更改,您可以在此处阅读:https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content

关于java - Spring ResponseStatusException 不返回原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62561211/

相关文章:

wcf - 如何使用 WCF/Rest Web 服务更新 sharepoint 中的多选字段?

Java 扫描器无法读取

java - 从 cmd 编译 java 程序时,我得到 "error: cannot find symbol",但在 Eclipse 中却没有

java - Spring Boot - 创建 HTTPS 连接不起作用

python - 单页应用程序 + REST 后端的用户管理

rest - 增加 Karaf 中 Jetty 线程池的大小

java - 使用 maven 构建应用程序

java - 如何在servlet中获取登录密码

java - 使用模拟测试时无法注入(inject)application.properties中定义的@value

spring-boot - 将几乎所有请求重定向到index.html