[英]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元素responseText
, status
和statusText
,因为我的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.