简体   繁体   中英

How to display error message into a Json using ResponseStatusException on Spring boot?

I have an issue displaying an error message at the moment that a bad request is triggered.

@DeleteMapping("/{projectId}/bugs/{bugId}")
public void deleteBug(@PathVariable (value = "projectId") Long projectId,
                      @PathVariable (value = "bugId") Long bugId){
    if (!projectService.existById(projectId) || !bugService.existById(bugId)) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ProjectId " + projectId + " or BugId " + bugId + " not found");
    }
    bugService.deleteBug(bugId);
}

This is the JSON response when I trigger the Response:

{
"timestamp": "2020-05-29T15:40:41.302+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/projects/3/bugs/2"  }

As you can see the message is not appearing. If I change the HttpStatus in the code it actually works but for some reason, the message is not working.

I checked the constructor of the class and it actually allows only the status and the reason.

Am I missing something or is it a bug in the ResponseStatusException class?

I also encountered this. It's not a bug, so downgrading is not the best resolution. The Spring Boot 2.3.0 release notes explain:

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 .

So for example, in your application configuration you can set these to show message but not trace output (YAML example):

server:
  error:
    include-message: ALWAYS
    include-stacktrace: NEVER

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM