Spring ResponseStatusException 不返回原因 [英] Spring ResponseStatusException does not return reason

查看:19
本文介绍了Spring ResponseStatusException 不返回原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的@RestController,我正在尝试设置自定义错误消息.但是由于某种原因,错误的message没有显示出来.

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,但我没有验证任何内容,我只是想设置自定义消息.如果我更改状态代码,我会在响应中看到它,但 message 始终为空.

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 中已更改,您可以在此处阅读: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆