Spring MVC Exception HandlerComments: 7
In previous version of Spring Framework to handle exception we used HandlerExceptionResolver interface. Spring also provides simple implementations which was suitable in most of cases. Since 3.0 version we have few additional exception resolvers plus we can use annotation to specify our exception handler methods or classes without implementing HandleExceptionResolver interface.
- AnnotationMethodHandlerExceptionResolver (new in 3.0)
- ResponseStatusExceptionResolver (new in 3.0)
- DefaultHandlerExceptionResolver (new in 3.0)
Should be configured in XML, there are few properties which drives this resolver behaviors.
- defaultErrorView -> this view name will be returned if no mapping will be found.
- defaultStatusCode -> once the view name was resolved if the view hasn’t status code the defaultStatusCode will be applied.
- statusCodes -> Map with “view name” to “status code” mapping.
- exceptionAttribute -> the name of attribute where exception is hold by default “exception” is used.
- exceptionMappings -> Properties which maps Exception “class name” to “view name”. Watch out as you can easily maps more than you want, this is because only String.contains is checked, so a=viewName mapping will catch all exception with “a” in the name.
Another thing to consider is that if you provide deep Exception hierarchy (n) and you provide a lot of exception mapping (m), you will end up with O(n*m) lookup algorithm. It may seem not problem, but if somebody spots that (Error page which render time is quite long), than it may be used with DDOS to increase load on ours machines.
First at all it has pageNotFound logger which is org.springframework.web.servlet.PageNotFound logger category, second it decides what to do depending on exception type, it is base class to extend when we want change default behavior:
- NoSuchRequestHandlingMethodException : no request handler method was found by default it sends 404 error. Override handleNoSuchRequestHandlingMethod.
- HttpRequestMethodNotSupportedException : no request handler method was found for the particular HTTP request method by default 405 error.Override handleHttpRequestMethodNotSupported.
- HttpMediaTypeNotSupportedException : no HttpMessageConverter were found for the PUT or POSTed content by default 415 error. Override handleHttpMediaTypeNotSupported.
- HttpMediaTypeNotAcceptableException : no HttpMessageConverter were found that were acceptable for the client (Accept header) by default 406 error. Override handleHttpMediaTypeNotAcceptable.
- MissingServletRequestParameterException : required parameter is missing by default 400 error. Override handleMissingServletRequestParameter.
- ConversionNotSupportedException : WebDataBinder conversion cannot occur by default 500 error. Override handleConversionNotSupported.
- TypeMismatchException : WebDataBinder conversion error occurs by default 400. Override handleTypeMismatch.
- HttpMessageNotReadableException : HttpMessageConverter cannot read from HTTP request by default 400 error. Override handleHttpMessageNotReadable.
- HttpMessageNotWritableException : HttpMessageConverter cannot write to HTTP response by default 500 error. Override handleHttpMessageNotWritable.
- ResponseStatus.value as status code (it is HttpStatus enum)
- ResponseStatus.reason as reason or default HttpResponse reason if not set.
Last but not least, and from my point of view this resolver is the most important. This exception resolver allows us to use @ExceptionHandler annotation, every method annotated by @ExceptionHandler will become exception handler. As parameters @ExceptionHandler need an array of Throwable. We also should use @ResponseStatus to indicate status code.
The method signatures possibilities are vary so see documentation to get all the proper combinations of parameters and return types.
The idea is pretty simple, for all the ExceptionHandler.value exception the exception -> Method handler is created, when Exception happens Method will be invoked.
Since 3.0 we rather has no need to setup handlers by ourself, the most useful way is to use @ExceptionHandler annotation. By default DispatcherServlet will setup AnnotationMethodHandlerExceptionResolver, ResponseStatusExceptionResolver and DefaultHandlerExceptionResolver as handlers resolvers. So we are ready to start with annotation based approach.
My approach is that I try to create moduleExceptionHandler class which has all methods annotated by @ExceptionHandler (except utility methods of course) and I always annotate them by @ResponseStatus as well. The methods parameters and return type vary depending on my needs. It a little bit central approach but it avoids problem with more than one handler per Exception.