Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

Exception message not included in response when throwing ResponseStatusException in Spring Boot

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());
        }
    }
}

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"
}

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

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

This is the exception class:

public class InvalidFormatException extends RuntimeException {

    public InvalidFormatException(String s1, String s2) {
        super(String.format("Invalid format: [s1: %s, s2: %s]", s1, s2));
    }
}
question from:https://stackoverflow.com/questions/62459836/exception-message-not-included-in-response-when-throwing-responsestatusexception

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...