且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

修改来自Spring Boot Rest Controller的默认JSON错误响应

更新时间:2021-11-18 00:06:21

As described in the documentation on error handling, you can provide your own bean that implements ErrorAttributes to take control of the content.

一种简单的方法是将DefaultErrorAttributes子类化.例如:

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

   };
}