首页 > 解决方案 > 如何在 Spring MVC 中设置错误响应状态的消息?

问题描述

我有一个这样的spring mvc处理程序:

    @PostMapping("jwtToken")
    fun jwtToken(@RequestBody body: JWTToken)
    {
        val token = body.token
        if(token.isNullOrBlank())
            throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Empty token")

    }

如果我向它发送一个不正确的输入,这会触发异常,我会得到一个这样的响应体:


{
  "timestamp": "2020-10-30T03:41:20.305+00:00",
  "status": 401,
  "error": "Unauthorized",
  "message": "",
  "path": "/auth/jwtToken"
}

当我为异常分配消息时,为什么响应中的“消息”字段为空?如何设置消息字段

标签: springspring-bootspring-mvc

解决方案


它可能与 Spring Boot 的更新行为有关。

https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content

server.error.include-message=always

in .properties 应该可以解决问题,但我更喜欢使用我自己的扩展类,如下所示:

class CustomException(message: String): Exception(message) { ... }

推荐阅读