且构网

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

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

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

关于错误处理的文档,您可以提供自己的 bean 来实现 ErrorAttributes 来控制内容.

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

   };
}