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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29106637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:48:06  来源:igfitidea点击:

Modify default JSON error response from Spring Boot Rest Controller

jsonspringrestspring-boot

提问by Marco

Currently the error response from spring boot contains the standard content like below:

目前 spring boot 的错误响应包含如下标准内容:

{
   "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?

我正在寻找一种方法来摆脱响应中的“异常”属性。有没有办法实现这一目标?

回答by Andy Wilkinson

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

错误处理文档中所述,您可以提供自己的 bean 来实现ErrorAttributes对内容的控制。

An easy way to do that is to subclass DefaultErrorAttributes. For example:

一个简单的方法是将DefaultErrorAttributes. 例如:

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

   };
}

回答by Lubo

If there is empty message text in json when you encounter exception, you can be hit by changed behavior in spring boot 2.3.0. If this is the case, just change your server.error.messageproperty to always.

如果遇到异常时 json 中的消息文本为空,则可能会被spring boot 2.3.0 中的更改行为击中。如果是这种情况,只需将您的server.error.message属性更改为always

回答by Vinay Vissh

Following answer is totally derived from Andy Wilkinson'sanswer (which uses web.reactiveclasses)
- It includes web.servletbased classes.
- Spring boot 2.2.4.RELEASE

以下答案完全源自Andy Wilkinson 的答案(使用web.reactive类)
- 它包括web.servlet基于类。
- 弹簧靴 2.2.4.RELEASE

ExceptionHandlerConfig.java

ExceptionHandlerConfig.java

package com.example.sample.core.exception;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.WebRequest;

@Configuration
public class ExceptionHandlerConfig {

    //private static final String DEFAULT_KEY_TIMESTAMP = "timestamp";
    private static final String DEFAULT_KEY_STATUS = "status";
    private static final String DEFAULT_KEY_ERROR = "error";
    private static final String DEFAULT_KEY_ERRORS = "errors";
    private static final String DEFAULT_KEY_MESSAGE = "message";
    //private static final String DEFAULT_KEY_PATH = "path";

    public static final String KEY_STATUS = "status";
    public static final String KEY_ERROR = "error";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_TIMESTAMP = "timestamp";
    public static final String KEY_ERRORS = "errors";

    //

    @Bean
    public ErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes() {

            @Override
            public Map<String ,Object> getErrorAttributes(
                WebRequest webRequest
                ,boolean includeStackTrace
            ) {
                Map<String ,Object> defaultMap
                    = super.getErrorAttributes( webRequest ,includeStackTrace );

                Map<String ,Object> errorAttributes = new LinkedHashMap<>();
                // Customize.
                // For eg: Only add the keys you want.
                errorAttributes.put( KEY_STATUS, defaultMap.get( DEFAULT_KEY_STATUS ) );                    
                errorAttributes.put( KEY_MESSAGE ,defaultMap.get( DEFAULT_KEY_MESSAGE ) );

                return errorAttributes;
            }
        };
    }
}