【问题标题】:For 400 Bad Request not getting proper error message对于 400 Bad Request 没有得到正确的错误信息
【发布时间】:2020-06-22 16:22:19
【问题描述】:

我们的控制器看起来像这样 -

@RestController
@RequestMapping(value="api")
@Validated
public class SampleController {
@RequestMapping(value = {"/test"}, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void test(
        @RequestParam(value = "testCode",required=true) String merchantCode
        ) throws Exception{
    System.out.print("This is Test");
}
}

如果我们没有在我们的请求中指定必需的参数“testCode”,我们会得到“400 Bad Request”,但错误响应的消息部分保持空白。

我们得到的回应 -

{"timestamp":1592441286607,"status":400,"error":"Bad Request","message":"","path":"/test"}

但预期是-

{"timestamp":1592441286607,"status":400,"error":"Bad Request","message":"Required String parameter 'testCode' is not present","path":"/test"}

我们正在使用下面的 Spring 依赖项 -

<spring-boot.version>2.3.0.RELEASE</spring-boot.version>
<spring-framework.version>5.2.6.RELEASE</spring-framework.version>

我所看到的是,为此我们得到了 MissingServletRequestParameterException,但在异常中消息以空白(“”)的形式出现。

【问题讨论】:

  • 如果您想要自定义消息,您可能必须创建自定义验证器。看看这里stackoverflow.com/questions/36823263/…
  • 不,实际上不是自定义消息。我要说的是消息部分本身是空白的。我在这里期待默认消息。
  • 相同的代码在spring boot 2.2.6版本中运行

标签: java spring spring-boot


【解决方案1】:

我刚刚用server.error.include-message=always 更新了bootstrap.yml。从 Spring 2.3.0 开始,Spring 的默认行为似乎发生了变化。我们可以参考以下链接了解更多详情https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content

【讨论】:

    【解决方案2】:

    application.yml 中的配置

    server:
      error:
        include-message: always
        include-binding-errors: always
        include-stacktrace: on_trace_param
        include-exception: true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-26
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多