Ours is a Spring MVC based REST application. I am trying to use ExceptionHandler annotation to handle all errors and exceptions.
I have
@ExceptionHandler(Throwable.class)
public @ResponseBody String handleErrors() {
return "error";
}
This works whenever there is an exception thrown and it doesn't work for any errors.
I am using Spring 4.0. Is there any work-around?
You have to provide implementation to use your error handler, map the response to response entity and throw the exception. Create new error exception class with ResponseEntity field. Custom error handler which maps the error response back to ResponseEntity.
The differences between @RestControllerAdvice and @ControllerAdvice is : @RestControllerAdvice = @ControllerAdvice + @ResponseBody . - we can use in REST web services. @ControllerAdvice - We can use in both MVC and Rest web services, need to provide the ResponseBody if we use this in Rest web services.
If no exception handler for a given exception is present, the program stops executing with an error message. Don't catch an exception unless you can handle it and leave the application in a known state.
Go to the flow of the REST API method or the callback (such as OnAuthentication or OnRequest) where you want to throw the error and add a Raise Error element. Set the Exception property to the User Exception you have created. Set the Exception Message property to your custom error message.
Contrary to what the ExceptionHandler#value()
attribute indicates
Class<? extends Throwable>[] value() default {};
and @ExceptionHandler
is only meant to handle Exception
and its sub types.
Spring uses ExceptionHandlerExceptionResolver
to resolve your annotated handlers, using the following method
doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod, Exception exception)
which as you can see only accepts an Exception
.
You cannot handle Throwable
or Error
types with @ExceptionHandler
with this configuration.
I would tell you to provide your own HandlerExceptionResolver
implementation which does handle Throwable
instances, but you'd need to provide your own DispatcherServlet
(and most of the MVC stack) yourself since DispatcherServlet
does not catch
Throwable
instances at any place where you could make any significant difference.
Update:
Since 4.3, Spring MVC wraps a thrown Throwable
value in a NestedServletException
instance and exposes that to the ExceptionHandlerExceptionResolver
.
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