As @zeroflagL mentioned, Spring Boot fabricates the "standard" error response body in org.springframework.boot.autoconfigure.web.DefaultErrorAttributes
. Similar to your needs, I wanted to leverage all of that, but simply augment one more "type" field that was provided by some of my exceptions.
I did that by implementing a Component
that sub-classed DefaultErrorAttributes
. Spring Boot automatically picked it up and used mine instead of the default.
@Component
public class ExtendedErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace) {
final Map<String, Object> errorAttributes =
super.getErrorAttributes(requestAttributes,
includeStackTrace);
final Throwable error = super.getError(requestAttributes);
if (error instanceof TypeProvider) {
final TypeProvider typeProvider = (TypeProvider) error;
errorAttributes.put("type", typeProvider.getTypeIdentifier());
}
return errorAttributes;
}
}
With that, I get an augmented JSON response body, such as
{
"timestamp": 1488058582764,
"status": 429,
"error": "Too Many Requests",
"exception": "com.example.ExternalRateLimitException",
"message": "DAILY_LIMIT: too many requests",
"path": "/api/lookup",
"type": "DAILY_LIMIT"
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…