-
Notifications
You must be signed in to change notification settings - Fork 41.6k
Description
When using ResponseEntityExceptionHandler
, by either creating a parent class
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {}
or enabling ProbleDetails
via the application configuration
spring:
mvc:
problemdetails:
enabled: true
the proper error format (i.e., ProbleDetails
) is used for some errors (e.g. 400
)
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Required parameter 'id' is not present.",
"instance": "/users"
}
but when an Exception
is thrown anywhere inside the code, which results in a 500
error then the default Spring Boot error format is returned instead
{
"timestamp": "2023-06-02T02:39:40.184+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/users"
}
this is quite confusing as it means that when enabling the ProblemDetails
format, it is not used for every error but only for a subset, and the clients that call the API need to handle 2 different error formats.
A way to fix this in the app is to create a method that handles the extra errors
@ControllerAdvice
public class ErrorHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Throwable.class)
public ProblemDetail handleExceptions(Throwable exception) {
return ProblemDetail.forStatus(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
but this feels like a hack that shouldn't be necessary, as errors should always be returned in the same format from Spring Boot (regardless of the format selected).
I think this would probably be fixed by adding the method shown above inside the ResponseEntityExceptionHandler
class, but this would break backward compatibility so I'm unsure if this should be released before the next major version release or if it can indeed be released in the current major version as a bug fix.
If you are happy with the approach I mentioned above I can create a PR for it.