首页 > 解决方案 > 关于 ResponseStatusException 返回错误对象中的空消息字段

问题描述

我在 Spring Boot 中有以下 API 端点:

@GetMapping("/metrics/{id}")
public MetricItem helperMethod(@PathVariable String id) {

        try {
            return customMetricRepository.find(id);
        } catch (IllegalArgumentException | NullPointerException | MetricDoestNotExistException  e) {

            if (e instanceof MetricDoestNotExistException) {
                throw new ResponseStatusException(
                        HttpStatus.NOT_FOUND, "Metric does not exist", e);
            }
            else {
                throw new ResponseStatusException(
                        HttpStatus.BAD_REQUEST, ErrorCodes.UUID_NOT_FOUND, e);
            }
        }
}

当找不到指标时,我想在对象的错误字段的消息字段中看到我的“指标不存在”,但我得到以下信息:

{
   "timestamp": "2020-07-01T22:53:44.494+00:00",
   "status": 404,
   "error": "Not Found",
   "message": "",
   "path": "/api/metrics/e1571021-6a17-4b02-b238-72ac3a1c26cd"
 }

标签: spring-bootresterror-handling

解决方案


we just had the same issue. I found a github discussion where someone pointed out that there was a change within spring-boot 2.3.
https://github.com/spring-projects/spring-boot/issues/22049

If you look into the release notes you can find this section:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content
There it says:
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.


推荐阅读