Alex Rivera | Logout

How to handle exceptions thrown while rendering a view in Spring MVC?

Asked 2012-06-28T13:37:39.473
29

I have a Spring MVC application which uses FreeMarker as View technology (But maybe the view technology doesn't really matter for my question). I need to intercept all exceptions which may get thrown during a request.

I have implemented a HandlerExceptionResolver but this resolver is only executed when the exception occurs within a controller. But when a controller returns a ModelAndView and the exception occurs while rendering the view (Because a variable was not found or something like this) then the exception resolver is not called and instead I get a stack trace in the browser window.

I also tried using an exception handler method within the controller which returns the view and annotated it with @ExceptionHandler but this also doesn't work (Most likely again because the exception is not thrown in the controller but in the view).

So is there some Spring mechanism where I can register an exception handler which captures view errors?

Edit
Report

1 Answer

0

Not sure if my solution works with the problem you're having. Ill just post the way i catch my exceptions to ensure no stack trace is show inside the browser:

I made an AbstractController class with a method that will handle a specific conflict like this:

public class AbstractController {

    @ResponseStatus(HttpStatus.CONFLICT)
    @ExceptionHandler({OptimisticLockingFailureException.class})
    @ResponseBody
    public void handleConflict() {
    //Do something extra if you want
    }
}

This way whenever an exception occurs the user will see a default HTTPResponse status. (eg. 404 Not Found etc..)

I extend this class on all my controller classes to make sure errors are redirected to the AbstractController. This way I don't need to use ExceptionHandler on a specific controller but I can add the globally to all my controllers. (by extending the AbstractController class).

Edit: After another go on your question, I noticed you're getting errors in your view. Not sure if this way will catch that error..

Hope this helps!!

answered 2012-06-28T13:43:21.913

Your Answer