以下Spring引导documentation我定义了自己的ErrorAttributes bean(见下文),我能够使json响应显示我想要的信息,包括我自己的错误代码和消息通过使用自定义异常来包装该信息并从中生成错误响应。唯一的问题是响应的http状态与我在状态属性中定义的状态不匹配,它没有被覆盖。Spring Boot自定义ErrorAttributes http状态未设置为响应
@Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
Throwable error = getError(requestAttributes);
if (error instanceof MyException) {
MyException myException = (MyException) error;
errorAttributes.put("errorCode", myException.getErrorCode());
errorAttributes.put("message", myException.getMessage());
errorAttributes.put("status", myException.getStatus());
HttpStatus correspondentStatus = HttpStatus.valueOf(myException.getStatus());
errorAttributes.put("error", correspondentStatus.getReasonPhrase());
}
return errorAttributes;
}
};
}
响应的HTTP状态不匹配的JSON的状态,例如:
HTTP/1.1 500
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 01 Mar 2017 18:48:22 GMT
{
"timestamp": "2017-03-01T18:48:21.894+0000",
"status": 403,
"error": "Forbidden",
"exception": "com.myapp.MyException",
"message": "You are not authorized. This user doesn't exist in the db",
"path": "/account",
"errorCode": "00013"
}
每http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/web/DefaultErrorAttributes.html#getErrorAttributes-org.springframework.web.context .request.RequestAttributes-boolean-您正在覆盖的方法不会更改http状态代码 – xiumeteo