Spring ResponseStatusException不返回原因 [英] Spring ResponseStatusException does not return reason
问题描述
我有一个非常简单的 @RestController
,并且我试图设置一个自定义错误消息。但是由于某种原因,错误的消息
没有显示。
I have a very simple @RestController
, and I'm trying to set a custom error message. But for some reason, the message
for the error is not showing up.
这是我的控制器:
@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,但我没有进行任何验证,我只是在尝试设置自定义消息。如果更改状态代码,则会在响应中看到该消息,但是消息
始终为空。
I'm passing a JSON, but I'm not validating anything, I'm just trying to set the custom message. If I change the status code, I see that on the response, but the message
is always empty.
为什么这不起作用像预期的那样?这是一个非常简单的示例,我看不到可能遗漏的内容。当我调试代码时,我可以看到错误消息设置了所有字段。但是由于某些原因,该消息永远不会在响应中设置。
Why is this not working like expected? This is such a simple example that I can't see what may be missing. When I debug the code I can see that the error message has all the fields set. But for some reason, the message is never set on the response.
推荐答案
此答案由用户Hassan在对以下内容的评论中提供原来的问题。我只是将其发布为答案,以使其具有更好的可见性。
This answer was provided by user Hassan in the comments on the original question. I'm only posting it as an answer to give it better visibility.
基本上,您所需要做的就是添加 server.error.include-message = always
到application.properties文件,现在应该填充您的消息字段。
Basically, all you need to do is add server.error.include-message=always
to your application.properties file, and now your message field should be populated.
此行为已在Spring Boot 2.3中更改,您可以在此处阅读: a href = https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content rel = noreferrer > https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content
This behavior was changed in Spring Boot 2.3 which you can read about here: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content
这篇关于Spring ResponseStatusException不返回原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!