Spring MVC exception handling

How to handle exceptions thrown by Spring MVC Controllers

In your controllers you (may) have code that throw exceptions, some of them are thrown in order to tell you that you should display an error to the user (I’m not talking about unexpected runtime exceptions 🙂 ).

Imagine that you use that piece of code in three different Spring controllers, you have to handle this exception three times.

Instead of doing that, you can let the exception go (by adding a throws clause in your method signature) and handle the exception differently, using a method annotated with @ExceptionHandler.

Here you go :

  • Controller layer

Declare a method in your Spring controller (or use a controller-assistant-class by defining a class annotated with @ControllerAdvice)

This method will be called each time a “MyException” exception is thrown.

public ModelAndView handleMyException(MyException exception) {
    // Always log exceptions
    // Path to your JSP
    ModelAndView modelAndView = new ModelAndView("my-custom-folder/error");
    // Add info in the model, for instance a custom error message
    modelAndView.addObject("errorMessage", "Ooops something went wrong.");
    return modelAndView;
  • View layer

Create the file “error.jsp” under the folder ”WEB-INF/jsp/my-custom-folder”. Use this JSP to display your beautiful error to the user.

You can use every piece of data you put in your model, in this example you can display the message set in the variable “errorMessage”

Et voila! Now when a MyException is thrown the user will always be redirected to the JSP error.jsp.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.