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

时间:2015-06-15 12:06:55

标签: json spring spring-boot spring-restcontroller

当控制器以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 here

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

1 个答案:

答案 0 :(得分:3)

您需要让Spring了解您的CustomErrorAttribute实施。

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

@Configuration
public class MvcErrorConfig {

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

}

并且一切都开箱即用。

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

相关问题