Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions in Spring MVC differently for HTML and JSON requests

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?

like image 591
kayahr Avatar asked May 10 '14 14:05

kayahr


People also ask

How many ways can you handle exceptions in Spring MVC?

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.

How does Spring MVC handle custom 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.

How do you handle exceptions in a Spring web application?

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.

Which of the following code shows how exceptions are handled in MVC?

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.


1 Answers

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 { 
like image 182
dnang Avatar answered Oct 07 '22 02:10

dnang