I'm using the following exception handler in Spring 4.0.3 to intercept exceptions and display a custom error page to the user:
@ControllerAdvice public class ExceptionHandlerController { @ExceptionHandler(value = Exception.class) public ModelAndView handleError(HttpServletRequest request, Exception e) { ModelAndView mav = new ModelAndView("/errors/500")); mav.addObject("exception", e); return mav; } }
But now I want a different handling for JSON requests so I get JSON error responses for this kind of requests when an exception occurred. Currently the above code is also triggered by JSON requests (Using an Accept: application/json
header) and the JavaScript client doesn't like the HTML response.
How can I handle exceptions differently for HTML and JSON requests?
Our goal is to not handle exceptions explicitly in Controller methods where possible. They are a cross-cutting concern better handled separately in dedicated code. There are three options: per exception, per controller or globally. http://github.com/paulc4/mvc-exceptions.
Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.
Spring provides two approaches for handling these exceptions: Using XML configuration: this is similar to exception handling in Servlet/JSP, by declaring a SimpleMappingExceptionResolverbean in Spring's application context file and map exception types with view names.
HandleError Attribute This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web. config.
The ControllerAdvice annotation has an element/attribute called basePackage which can be set to determine which packages it should scan for Controllers and apply the advices. So, what you can do is to separate those Controllers handling normal requests and those handling AJAX requests into different packages then write 2 Exception Handling Controllers with appropriate ControllerAdvice annotations. For example:
@ControllerAdvice("com.acme.webapp.ajaxcontrollers") public class AjaxExceptionHandlingController { ... @ControllerAdvice("com.acme.webapp.controllers") public class ExceptionHandlingController {
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