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"
}
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With