Spring MVC Exception Handling

Spring MVC Exception Handling is very important to make sure you are not sending server exceptions to client. Today we will look into Spring Exception Handling using @ExceptionHandler, @ControllerAdvice and HandlerExceptionResolver. Any web application requires good design for exception handling because we don’t want to serve container generated page when any unhandled exception is thrown by our application.

Spring Exception Handling

Having a well defined exception handling approach is a huge plus point for any web application framework, that being said Spring MVC framework delivers well when it comes to exception and error handling in our web applications.

Spring MVC Framework provides following ways to help us achieving robust exception handling.

  1. Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation. This annotation takes Exception class as argument. So if we have defined one of these for Exception class, then all the exceptions thrown by our request handler method will have handled.These exception handler methods are just like other request handler methods and we can build error response and respond with different error page. We can also send JSON error response, that we will look later on in our example.If there are multiple exception handler methods defined, then handler method that is closest to the Exception class is used. For example, if we have two handler methods defined for IOException and Exception and our request handler method throws IOException, then handler method for IOException will get executed.
  2. Global Exception Handler – Exception Handling is a cross-cutting concern, it should be done for all the pointcuts in our application. We have already looked into Spring AOP and that’s why Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.The handler methods in Global Controller Advice is same as Controller based exception handler methods and used when controller class is not able to handle the exception.
  3. HandlerExceptionResolver – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.SimpleMappingExceptionResolver is the default implementation class, it allows us to configure exceptionMappings where we can specify which resource to use for a particular exception. We can also override it to create our own global handler with our application specific changes, such as logging of exception messages.

Let’s create a Spring MVC project where we will look into the implementation of Controller based, AOP Based and Exception Resolver Based exception and error handling approaches. We will also write a exception handler method that will return JSON response. If you are new to JSON in Spring, read Spring Restful JSON Tutorial.

Our final project will look like below image, we will look at all the components of our application one by one.

Spring-MVC-Exception-Handling-Project-255x450

Spring Exception Handling Maven Dependencies

Apart from standard Spring MVC dependencies, we would also need Jackson JSON dependency for JSON support.

Our final pom.xml file looks like below.

I have updated Spring Framework, AspectJ, Jackson and slf4j versions to use the latest one.

Spring MVC Exception Handling Deployment Descriptor

Our web.xml file looks like below.

Most of the part is for plugging in Spring Framework for our web application, except the error-page defined for 404 error. So when our application will throw 404 error, this page will be used as response. This configuration is used by container when our spring web application throws 404 error code.

Spring Exception Handling – Model Classes

I have defined Employee bean as model class, however we will be using it in our application just to return valid response in specific scenario. We will be deliberately throwing different types of exceptions in most of the cases.

Since we will be returning JSON response too, let’s create a java bean with exception details that will be sent as response.

Spring Exception Handling – Custom Exception Class

Let’s create a custom exception class to be used by our application.

Notice that we can use @ResponseStatus annotation with exception classes to define the HTTP code that will be sent by our application when this type of exception is thrown by our application and handled by our exception handling implementations.

As you can see that I am setting HTTP status as 404 and we have an error-page defined for this, so our application should use the error page for this type of exception if we are not returning any view.

We can also override the status code in our exception handler method, think of it as default http status code when our exception handler method is not returning any view page as response.

Spring MVC Exception Handling Controller Class Exception Handler

Let’s look at our controller class where we will throw different type of exceptions.

Notice that for EmployeeNotFoundException handler, I am returning ModelAndView and hence http status code will be sent as OK (200). If it would have been returning void, then http status code would have been sent as 404. We will look into this type of implementation in our global exception handler implementation.

Since I am handling only EmployeeNotFoundException in controller, all other exceptions thrown by our controller will be handled by global exception handler.

@ControllerAdvice and @ExceptionHandler

Here is our global exception handler controller class. Notice the class is annotated with @ControllerAdvice annotation. Also methods are annotated with @ExceptionHandler annotation.

Notice that for SQLException, I am returning database_error.jsp as response page with http status code as 200.

For IOException, we are returning void with status code as 404, so our error-page will be used in this case.

As you can see that I am not handling any other types of exception here, that part I have left for HandlerExceptionResolver implementation.

HandlerExceptionResolver

We are just extending SimpleMappingExceptionResolver and overriding one of the method, but we can override it’s most important method resolveException for logging and sending different types of view pages. But that is same as using ControllerAdvice implementation, so I am leaving it. We will be using it to configure view page for all the other exceptions not handled by us by responding with generic error page.

Spring Exception Handling Configuration File

Our spring bean configuration file looks like below.

spring.xml code:

Notice the beans configured for supporting JSON in our web application. The only part related to exception handling is the simpleMappingExceptionResolver bean definition where we are defining generic_error.jsp as the view page for Exception class. This make sure that any exception not handled by our application will not result in sending server generated error page as the response.

Spring MVC Exception Handling JSP View Pages

It’s time to look into the last part of our application, our view pages that will be used in our application.

home.jsp code:

home.jsp is used to respond with valid data, i.e when we get id as 10 in the client request.

404.jsp code:

404.jsp is used for generating view for 404 http status code, for our implementation this should be the response when we get id as 3 in client request.

error.jsp code:

error.jsp is used when our controller class request handler method is throwing EmployeeNotFoundException. We should get this page in response when id value is 1 in the client request.

database_error.jsp code:

database_error.jsp is used when our application is throwing SQLException, as configured in GlobalExceptionHandler class. We should get this page as response when id value is 2 in the client request.

generic_error.jsp code:

This should be the page as response when any exception occurs not handled by our application code and simpleMappingExceptionResolver bean takes care of that. We should get this page as response when id value in client request is anything other than 1,2,3 or 10.

Running the Spring MVC Exception Handling Application

Just deploy the application in the servlet container you are using, I am using Apache Tomcat 7 for this example.

Below images show the different response pages returned by our application based on the id value.

ID=10, valid response.

ID=1, controller based exception handler used

ID=2, global exception handler used with view as response

ID=3, 404 error page used

ID=4, simpleMappingExceptionResolver used for response view

As you can see that we got the expected response in all the cases.

Spring Exception Handler JSON Response

We are almost done with our tutorial, except the last bit where I will explain how to send JSON response from the exception handler methods.

Our application has all the JSON dependencies and jsonMessageConverter is configured, all we need to implement the exception handler method.

For simplicity, I will rewrite the EmployeeController handleEmployeeNotFoundException() method to return JSON response.

Just update EmployeeController exception handler method with below code and deploy the application again.

Now when we use id as 1 in client request, we get following JSON response as shown in the below image.

Spring-Exception-Handling-JSON-Response-450x77

That’s all for Spring Exception Handling and Spring MVC Exception Handling, please download the application from below URL and play around with it to learn more.

By admin

Leave a Reply