[英]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.