By default Spring Boot maps /error
to BasicErrorController
. I want to log the exception along with the request that causes the exception. How can I get the original request in BasicErrorController
or a new CustomErrorController
. It seems that Spring Boot will make a new request to /error
when an exception is thrown and the orginal request info is gone or no way to map the error with the original request.
Exception Handling in Spring Boot REST API. When you develop a Spring Bool RESTful service, you as a programmer are responsible for handling exceptions in the service. For instance, by properly handling exceptions, you can stop the disruption of the normal flow of the application.
Similarly, when dealing with REST requests, Spring Boot automatically returns a default JSON response in case of errors. This contains the same information as the aforementioned Whitelabel HTML error page and looks as follows: As you can see, the default Spring Boot error handling responses for REST does not provide much information.
The @ControllerAdvice annotation was introduced in Spring 3.2 to make exception handling logic easier and entirely definable in one place. In fact, @ControllerAdvice allows you to address exception handling across the whole application.
DefaultHandlerExceptionResolver This resolver was introduced in Spring 3.0, and it's enabled by default in the DispatcherServlet. It's used to resolve standard Spring exceptions to their corresponding HTTP Status Codes, namely Client error 4xx and Server error 5xx status codes.
Get it by:
String url = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
To avoid any misleading information, Spring Boot DOES NOT make a new request to /error
endpoint. Instead, it wraps the exception in the original request and forwards it to /error
endpoint. The request will be processed by BasicErrorHandler
if you don't provide a custom error handler.
In this case, if you are using an interceptor
, the interceptor will be invoked twice - one for the original request and the other for the forwarded request.
To retrieve the original request information, please look into the forwarded request's attributes. Basically, you can get the error message from these attributes javax.servlet.error.message, javax.servlet.error.status_code, org.springframework.web.servlet.DispatcherServlet.EXCEPTION
.
And these are some resources that are related to error handling in Spring Boot:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With