Thanks to DefaultErrorAttributes, Spring Boot by default returns a response body for exceptions that meets my needs out of the box:
{
"timestamp": 1588022957431,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"errors": [
{
"codes": [
"NotEmpty.myResource.label",
"NotEmpty.label",
"NotEmpty.java.lang.String",
"NotEmpty"
],
"arguments": [
{
"codes": [
"myResource.label",
"label"
],
"arguments": null,
"defaultMessage": "label",
"code": "label"
}
],
"defaultMessage": "must not be empty",
"objectName": "myResource",
"field": "label",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotEmpty"
}
],
"message": "Validation failed for object='myResource'. Error count: 1"
}
Furthermore, between the built-in exception handling provided by DefaultHandlerExceptionResolver and my own custom error handling, I have the exceptions returning exactly the response codes I want my REST API to be exposing.
What I would like to do is log the exceptions thrown for debugging purposes. If the exception results in a 4xx response, I'd like to log it as debug level, since that's a problem with the client's request, and not something I'll generally need logged in production (but which might be useful to have around when debugging specific issues or testing the correctness of the code). If it results in a 5xx exception, I would like to log it at warn level, since this indicates an unexpected problem with the server that I would likely want to be made aware of.
I do not see a good mechanism for adding in this logging while retaining both the default Spring Boot response body, as well as my customized status code mappings. How can I do this conditional logging based on status code while keeping my current response body & status codes? Even better, is there a way to do this that will also work with the few endpoints I have that use their own customized @ExceptionHandler methods to return a different response body?