2015-06-15 99 views
3

當控制器響應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元素responseTextstatus,並且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

,但沒有運氣,請任何幫助。謝謝。

+0

您可以發佈您配置'ErrorAttributes'的代碼嗎? – geoand

+0

Hello @geoand用'ErrorAttributes'實現更新了問題。 – Lovababu

+0

您是否配置了任何類型爲'ErrorAttributes'的Bean? – geoand

回答

3

您需要讓Spring知道您的CustomErrorAttribute實現。

只需添加一個配置類(或簡稱爲@Bean部件添加到您現有的Spring配置類之一),如:

@Configuration 
public class MvcErrorConfig { 

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

} 

,一切工作開箱。

This部分文檔包含所有細節。 相關的Spring Boot自動配置類是ErrorMvcAutoConfiguration

+0

我相信'CustomErrorAttribute'是Spring知道的,因爲我可以自動裝載它。 githug鏈接到我的項目https://github.com/lovababu/SpringBootExample – Lovababu

+0

好的,我運行該項目並回復給您 – geoand

+0

您的項目中的錯誤處理對我來說開箱即用。 Spring的'CustomErrorAttribute'類正在被正確使用。也許你應該執行'gradle clean'並看看會發生什麼 – geoand

相關問題