當控制器響應400-BadRequest時,我的彈簧引導應用程序返回低於json響應。如何覆蓋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
註冊自定義實現作爲指定here
,但沒有運氣,請任何幫助。謝謝。
您可以發佈您配置'ErrorAttributes'的代碼嗎? – geoand
Hello @geoand用'ErrorAttributes'實現更新了問題。 – Lovababu
您是否配置了任何類型爲'ErrorAttributes'的Bean? – geoand