java - 如何在 Spring 启动时使用 ResponseStatusException 将错误消息显示到 Json 中?

标签 java spring spring-boot spring-mvc

我在触发错误请求时显示错误消息时遇到问题。

@DeleteMapping("/{projectId}/bugs/{bugId}")
public void deleteBug(@PathVariable (value = "projectId") Long projectId,
                      @PathVariable (value = "bugId") Long bugId){
    if (!projectService.existById(projectId) || !bugService.existById(bugId)) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ProjectId " + projectId + " or BugId " + bugId + " not found");
    }
    bugService.deleteBug(bugId);
}

这是我触发响应时的 JSON 响应:
{
"timestamp": "2020-05-29T15:40:41.302+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/projects/3/bugs/2"  }

如您所见,该消息没有出现。如果我更改代码中的 HttpStatus,它实际上可以工作,但由于某种原因,该消息不起作用。

我检查了类的构造函数,它实际上只允许状态和原因。

我是遗漏了什么还是 ResponseStatusException 类中的错误?

最佳答案

我也遇到过这个。这不是错误,因此降级不是最佳解决方案。 Spring Boot 2.3.0 release notes解释:

Changes to the Default Error Page's Content

The error message and any binding errors are no longer included in the default error page by default. This reduces the risk of leaking information to a client. server.error.include-message and server.error.include-binding-errors can be used to control the inclusion of the message and binding errors respectively. Supported values are always, on-param, and never.



例如,在您的应用程序配置中,您可以将这些设置为显示 message但不是 trace输出(YAML 示例):

server:
  error:
    include-message: ALWAYS
    include-stacktrace: NEVER

关于java - 如何在 Spring 启动时使用 ResponseStatusException 将错误消息显示到 Json 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62089792/

相关文章:

java - 如何使用 Mask 从 JFormattedTextField 获取日期

java - 在 Spring MVC 表单中绑定(bind)嵌套属性

java - Spring DatastoreRepository beans无法在运行时解析,但Intellij在构建时没有显示错误

java - Sonar 覆盖范围为 0%,未生成 jacoco.xml

java - 使用 ssl 证书和 feign

java - YuiCompressorTask : "Can' t find bundle for base name org. mozilla.javascript.resources.Messages,区域设置 en_US"

java - 查找具有特定注释的加载类

Xmonad 中不显示 Java Swing GUI

spring - Aspectj - 拦截 HTTP 请求

java - SpringBoot项目gradle build 'bootRepackage'任务失败,因为无法重命名jar