How to overwrite default JSON response on Spring Boot

My spring boot app 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 don't want to see the json elements responseText

, status

and statusText

since the JSON object itself has this information.

Here is my class CustomErrorAttributes

.

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 configuration:

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

      

I tried to register a custom implementation of ErrorAttributes

both @Bean

as described here

But no luck please any help. Thank.

+3


source to share


1 answer


You need to tell Spring about your implementation CustomErrorAttribute

.

Just add a config class (or just add the part @Bean

to one of your existing Spring config 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 contains detailed information. The corresponding Spring Boot autoconfiguration class isErrorMvcAutoConfiguration

+3


source







All Articles