Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change ErrorAttributes of ResponseStatusException?

How can I change the error attributes that are exposed when throwing a ResponseStatusException?

Especially I want to hide the exception, error and status type in the json, but only during production.

    @RestController
    public class MyController {
       @GetMapping("/test")
       public Object get() {
          throw new org.springframework.web.server.ResponseStatusException(
                 HttpStatus.Forbidden, "some message");
       }
    }

Result:

{
    "timestamp": "2018-11-06T12:16:50.111+0000",
    "status": 403,
    "error": "Forbidden",
    "exception": "org.springframework.web.server.ResponseStatusException",
    "message": "some message",
    "path": "/test"
}
like image 638
membersound Avatar asked Nov 06 '18 12:11

membersound


People also ask

What is Response Status exception?

ResponseStatusException is a programmatic alternative to @ResponseStatus and is the base class for exceptions used for applying a status code to an HTTP response. It's a RuntimeException and hence not required to be explicitly added in a method signature.

How do you throw an exception in a response entity?

You have to provide implementation to use your error handler, map the response to response entity and throw the exception. Create new error exception class with ResponseEntity field. Custom error handler which maps the error response back to ResponseEntity.

How do I send a custom response in spring boot?

Steps. Please create a new package with the name 'response' in which we will create a class with the name “ResponseHandler”. This class will later be used to generate responses, where the response will be received in the form of an object with 3 parameters/values ​​in it.


1 Answers

It's configure using DefaultErrorAttributes

public DefaultErrorAttributes(boolean includeException)

Create a new DefaultErrorAttributes instance.

Parameters:

includeException - whether to include the "exception" attribute

Notice the default is without

public DefaultErrorAttributes()

Create a new DefaultErrorAttributes instance that does not include the "exception" attribute.

See example of customizing error

like image 158
user7294900 Avatar answered Sep 20 '22 12:09

user7294900