Question

There are countless articles explaining basic exception handling using Spring 3 MVC which I have successfully implemented. So now when one of my Controllers throws an Exception class it gets caught properly by my custom exception handler.

However, I cannot get it to throw Error classes to my custom exception handler and this is what I need. Some third party libraries throw Errors which simply bypass my Spring error handling configuration, which seems to be only for Exception and its sub-classes.

Is there any way I can configure it to also include Error types in my custom exception handler?

The following code demonstrates how I set mine up:

  <bean id="exceptionResolver" class="com.test.ExceptionHandler" p:order="2" >


    <property name="defaultErrorView" value="error"/>
  </bean>
Was it helpful?

Solution

The pattern we have used is to have a BaseController that all our Controllers extend using the following format to have specific errors mapped to specific HTTP status and a catch for more the most generic in Exception:

@Controller
public class BaseController {

    @ExceptionHandler (Exception.class)
    @ResponseStatus (HttpStatus.INTERNAL_SERVER_ERROR)
    public ModelAndView handleAllExceptions(Exception ex) {
        return new JsonError(ex.getMessage()).asModelAndView();
    }

    @ExceptionHandler (InvalidArticleQueryRangeException.class)
    @ResponseStatus (HttpStatus.NOT_FOUND)
    public ModelAndView handleAllExceptions(InvalidArticleQueryRangeException ex) {
        return new JsonError(ex.getMessage()).asModelAndView();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top