本文介绍了在 Spring Boot 中抛出 ResponseStatusException 时,响应中不包含异常消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Spring Boot 应用程序提供以下 REST 控制器:

My Spring Boot application provides the following REST controller:

@RestController
@RequestMapping("/api/verify")
public class VerificationController {

    final VerificationService verificationService;

    Logger logger = LoggerFactory.getLogger(VerificationController.class);

    public VerificationController(VerificationService verificationService) {
        this.verificationService = verificationService;
    }

    @GetMapping
    public void verify(
            @RequestParam(value = "s1") String s1,
            @RequestParam(value = "s2") String s2) {
        try {
            verificationService.validateFormat(s1, s2);
        } catch (InvalidFormatException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
        }
    }
}

如果 validateFormat() 抛出 InvalidFormatException,客户端会得到一个正确的 HTTP 400.然而,默认的 JSON 响应正文如下所示:

In case validateFormat() throws the InvalidFormatException the client gets a HTTP 400 which is correct. The default JSON response body however looks like this:

{
    "timestamp": "2020-06-18T21:31:34.911+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/api/verify"
}

message 值总是空的,即使我这样硬编码:

The message value is always empty even if I hard-code it like this:

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "some string");

这是异常类:

public class InvalidFormatException extends RuntimeException {

    public InvalidFormatException(String s1, String s2) {
        super(String.format("Invalid format: [s1: %s, s2: %s]", s1, s2));
    }
}

推荐答案

这种行为在 Spring Boot 2.3 中有所改变,并且是有意为之.参见 发行说明 了解详情.

This behavior has changed with Spring Boot 2.3 and is intentional. See release notes for details.

application.properties 中设置 server.error.include-message=always 可解决此问题.

Setting server.error.include-message=always in the application.properties resolves this issue.

这篇关于在 Spring Boot 中抛出 ResponseStatusException 时,响应中不包含异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:48