Custom 404 Exception Handling in Spring MVC

There are a number of excellent guides on creating custom 404 exceptions in Spring MVC. I read most of them. Like most tasks in Spring, there are a number of approaches you can take. Here is mine. You can find the source code of this post in the Version 0.1.5 Branch of NixMash Spring on GitHub.

Here are the exceptions we’ll be discussing. First a custom Contact Not Found exception.

Next, a custom 404 Resource Not Found exception.

A Contact Not Found Exception

An important thing to remember in handling a custom exception is to throw the exception. We’re going to do that from our Service layer in a minute, but we need an custom exception to throw. Here’s our ContactNotFoundException class extending Exception. These are typically very simple classes.

Now onto throwing the exception, which we’ll do in our Service FindContactById() method.

The exception is thrown. On to our MVC ContactController class. We have a method for RequestMapping of /contact/{id} which we’re not even going to look at because the only thing we do to add Contact Not Found Exception Handling is to add throws ContactNotFoundExceptionto the method signature.

We WILL look at a Controller method in our @ControllerAdvice ExceptionController class. This method is annotated with @ExceptionHandler(ContactNotFoundException.class). It will display our Thymeleaf error.html view.

A Custom 404 Resource Not Found Page

The elements of a Custom 404 page are similar to those we just covered in creating a custom exception page. We have a simple UnknownResourceException class, a ContractController method to test for a path that doesn’t exist and a @ControllerAdvice method to display our 404 page.

Here is perhaps the most interesting aspect of catching a Resource Not Found: the request path filter in the ContactController method. If we simply use a mapping of {“/**”} our Webjars, images and other static elements wouldn’t load, so any path not containing “webjars” or “static” if not meeting any other mappings are flagged by this mapping as an Unknown Resource.

We throw the UnknownResourceException exception and our @ControllerAdvice method handling UnknownResourceException.class takes care of the rest.

As I said at the outset, you’ll find the working source code for this post in the v0.1.5 branch of NixMash Spring on GitHub.