Currently the error response from spring boot contains the standard content like below:
{ "timestamp" : 1426615606, "exception" : "org.springframework.web.bind.MissingServletRequestParameterException", "status" : 400, "error" : "Bad Request", "path" : "/welcome", "message" : "Required String parameter 'name' is not present" }
I am looking for a way to get rid of the "exception" property in the response. Is there a way to achieve this?
The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.
Altogether, the most common way is to use @ExceptionHandler on methods of @ControllerAdvice classes so that the exception handling will be applied globally or to a subset of controllers. ControllerAdvice is an annotation introduced in Spring 3.2, and as the name suggests, is “Advice” for multiple controllers.
As described in the documentation on error handling, you can provide your own bean that implements ErrorAttributes
to take control of the content.
An easy way to do that is to subclass DefaultErrorAttributes
. For example:
@Bean public ErrorAttributes errorAttributes() { return new DefaultErrorAttributes() { @Override public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) { Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace); // Customize the default entries in errorAttributes to suit your needs return errorAttributes; } }; }
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