Modify default JSON error response from Spring Boo

2020-02-02 08:40发布

问题:

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?

回答1:

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;
        }

   };
}