Exception Handling in Spring MVC Application

There are times when even the best of applications fails to process a request, things may go wrong for multiple reasons like network errors, memory issue or some issue with the code. Whatever may be the case these error/ exceptions should always be translated into a response. This article deals with these unwanted situations when the Spring MVC Application throws an exception while request processing.

Spring provides multiple ways to translate exceptions into responses:

  1. Spring does some of the work for us, it automatically translates certain Spring exceptions to HTTP status codes.
  2. We can annotate exceptions with @ResponseStatus to map them to HTTP status codes.
  3. A method can be annotated with @ExceptionHandler to handle specific exceptions in the method.

Automatic translation of Spring Exceptions to HTTP status codes:

Spring translated some of its exception to HTTP status codes. The below table shows some of such mappings:

Exceptions Mapped Http Status Codes
BindException 400 - Bad Request



500 - Internal Server Error
HttpMediaTypeNotSupportedException 415 - Unsupported Media Type



400 - Bad Request
NoSuchRequestHandlingMethodException 404 - Not Found

Mapping exceptions to HTTP status codes:

To map any exception to a specific Http status code, Spring provides the @ResponseStatus annotation.

Let's consider a simple scenario where we are presented with a list of articles and on click of the article you will be taken to the article's content page.

We would throw an exception when an article is not found. Shown below is a custom exception which we would be thrown when an article is not found. You can download the complete application source code from the download link at the end of the article.

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Article Not Found")
public class ArticleNotFoundException extends RuntimeException {

Note that the @ResponseStatus annotation will map this exception to HttpStatus NOT_FOUND which is 404, with the message as specified in reason i.e. “Article Not Found”. Without this annotation the exception would result in 500 Internal Server Error.

Below is a piece of code which shows what happens in the service layer.

public Article getArticle(String articleId) {
    Article article = articleMap.get(articleId);
    if(article == null){
	throw new ArticleNotFoundException();
    return article;

Exceptions Handling Methods:

Apart from mapping exceptions to http status codes, we can also write exception handling methods in Spring controllers. These method would be called when a specific exception is thrown. For a method to have such a behaviour it should be annotated with @ExceptionHandler as shown below:

public String verifyAuth() {
    return "unauthorized";

In the above code snippet, the method would handle all AuthException thrown from the controller where the method is written. In this method we can write our own custom logic to handle the exception. In this case we are just showing a jsp view to the user indicating that he is trying to access a protected resource.

Download Source Code

You can download the source code of the sample Spring Application discussed in this article.


Creating Conditional Beans in Spring

The concept of condition beans enables Spring to restrict the creation of any bean depending on the evaluation of a condition. These beans get created only when a preset condition is evaluated as true

View Article

Accepting Request Param and Path Variable in Spring Controller

Spring MVC provides various ways through which a client browser can pass data to the Controller. In this article we will discuss about accepting Request Parameters and Path Variables in Spring Contr..

View Article

Generate Namespace & Schema Information using JAXB

Most xml documents used in enterprise applications makes use of namespace to avoid element name conflicts. This article talks about generating these namespace and schema information when marshaling...

View Article

Switching Database Profile using Spring Profiles

We are most likely to have separate db configuration for different environment like development and production environment. Spring profiles provide a convenient way to switch db profiles at runtime.

View Article

SQL and its Sub-Languages

SQL (Structured Query Language) is a language understood by most modern databases. It is an ANSI (American National Standard Institute) standard language which is used to manipulate databases.

View Article

Introducing JUnit Rule

Junit Rules allows developers to add additional functionalities that can applied to all test methods in a test class. It is similar to the concept of custom test runners but with reduced restrictions.

View Article

Addressing Ambiguity in Spring Autowiring

Spring autowiring is powerful concept, but we should be very cautious while using it. We may end up in creating ambiguity while autowiring beans, which will cause autowiring to fail.

View Article

Creating and Using Synonym in Oracle Database

Synonyms are database objects used to provide duplicate names to existing objects in the database. It is just an alternate name used to hide the original name of the object.

View Article

Creating and Using Sequence in Oracle Database

A sequence is used to auto-generate numbers in ascending or descending order which can serve as a primary key or a part of it (in case of composite key).

View Article

Creating and Manipulating Constraints in Oracle Database

Constraints are used to impose certain rules on columns to avoid invalid data entry into the table. If any of the constraint is violated the operation fails.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article

Tagging in GIT

Tagging allows us to mark a specific point in the commit history or snapshot. A tag is typically used to mark a project release. This article shows how to create tags in Git.

View Article