How to overwrite the default JSON response in Spring boot

2.2k views Asked by At

My spring boot application returning below json response when controller responds with 400-BadRequest.

{
  "readyState": 4,
  "responseText": "{\r\n  \"success\" : false,\r\n  \"projects\" :null,\r\n  \"httpStatusCode\" : \"400\",\r\n  \"message\" : \"Request  Processing failed.\",\r\n  \"requestErrors\" : [ {\r\n    \"error\" : \"platform required.\"\r\n  }, {\r\n    \"error\" : \"id required.\"\r\n  }, {\r\n    \"error\" : \"name required.\"\r\n  } ]\r\n}",
"responseJSON": {
"success": false,
"projects": null,
"httpStatusCode": "400",
"message": "Request Processing failed.",
"requestErrors": [
  {
    "error": "platform required."
  },
  {
    "error": "id required."
  },
  {
    "error": "name required."
  }
]
},
 "status": 400,
 "statusText": "Bad Request" 
}

But here i dont want to see json elements responseText, status, and statusText, since my JSON object itself having these information.

Here is my CustomErrorAttributes class.

public class CustomErrorAttribute implements ErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
    Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
    errorAttributes.put("timestamp", new Date());
    return errorAttributes;
}

@Override
public Throwable getError(RequestAttributes requestAttributes) {
    return new IllegalStateException("Illegal State of the request.");
}
}

Java Config:

@Bean
public ErrorAttributes customErrorAttribute(){
    return new CustomErrorAttribute();
}

I tried with registering custom implementation of ErrorAttributes as @Bean as specified here

But no luck, please any help. Thanks.

1

There are 1 answers

8
geoand On

You need to make Spring aware of your CustomErrorAttribute implementation.

Just add a configuration class (or simply add the @Bean part to one of your existing Spring configuration classes) like:

@Configuration
public class MvcErrorConfig {

    @Bean
    public CustomErrorAttribute errorAttributes() {
        return new CustomErrorAttribute();
    }

}

and everything works out of the box.

This part of the documentation has all the details. The relevant Spring Boot autoconfiguration class is ErrorMvcAutoConfiguration