08-02-2023, 04:25 PM
I'm using the following exception handler in Spring 4.0.3 to intercept exceptions and display a custom error page to the user:
<!-- Language: java -->
@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?
<!-- Language: java -->
@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?