繁体   English   中英

如何在Spring启动时覆盖默认的JSON响应

[英]How to overwrite the default JSON response in Spring boot

当控制器响应400-BadRequest时,我的spring启动应用程序返回到json响应之下。

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

但是在这里我不想看到json元素responseTextstatusstatusText ,因为我的JSON对象本身具有这些信息。

这是我的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配置:

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

我的注册自定义实现试过ErrorAttributes作为@Bean按规定这里

但没有运气,请任何帮助。 谢谢。

您需要让Spring知道您的CustomErrorAttribute实现。

只需添加一个配置类(或者只是将@Bean部分添加到现有的一个Spring配置类中),例如:

@Configuration
public class MvcErrorConfig {

    @Bean
    public CustomErrorAttribute errorAttributes() {
        return new CustomErrorAttribute();
    }

}

一切都开箱即用。

部分文档包含所有细节。 相关的Spring Boot自动配置类是ErrorMvcAutoConfiguration

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM