Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify default JSON error response from Spring Boot Rest Controller

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?

like image 984
Marco Avatar asked Mar 17 '15 18:03

Marco


People also ask

How do I send a custom error message in REST API spring boot?

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.

How do you handle exceptions in spring boot REST API?

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.


1 Answers

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;         }     }; } 
like image 151
Andy Wilkinson Avatar answered Sep 20 '22 09:09

Andy Wilkinson