4

当控制器响应 400-BadRequest 时,我的 Spring Boot 应用程序返回低于 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、、statusstatusText,因为我的 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指定的方式注册自定义实现

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

4

1 回答 1

3

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

只需添加一个配置类(或简单地将@Bean部分添加到现有的 Spring 配置类之一),例如:

@Configuration
public class MvcErrorConfig {

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

}

一切都开箱即用。

部分文档包含所有详细信息。相关的 Spring Boot 自动配置类是ErrorMvcAutoConfiguration

于 2015-06-15T12:24:03.207 回答