Home » Implementing Exception Handling- 404 Resource Not Found

Implementing Exception Handling- 404 Resource Not Found

by Online Tutorials Library

Implementing Exception Handling- 404 Resource Not Found

In the previous section, we had returned the proper response status of CREATED when we created the resource. In this section, we will discuss what should be the response when a user resource does not exist.

Let’s try and execute a simple response.

Step 1: Open Rest client Postman and select the Get method.

Step 2: Click on the History tab and choose the Get request.

Step 3: Type the URI http://localhost:8080/users/{id}. The user id should not exist.

Step 4: Click on the Send Button.

Implementing Exception Handling- 404 Resource Not Found

We get the Status: 200 OK and empty body which is a successful response even though the resource does not exist. But it is not the proper response when a resource does not exist.

Let’s fix that first.

Step 1: Open the UserResource.java file.

Step 2: Create a UserNotFoundException. It is a checked exception.

Step 3: Create UserNotFoundException class.

Step 4: Generate Constructors from Superclass.

Right-click on the file -> Source -> Generate Constructors from Superclass… -> check the RuntimeException(String) -> Generate.

Implementing Exception Handling- 404 Resource Not Found

UserNotFoundException.java

Step 5: Open the Rest Client Postman and generate a Get response as we have done before. It shows the Status: 500 Internal Server Error.

Implementing Exception Handling- 404 Resource Not Found

But the Status: 500 Internal Server Error is not the appropriate response for the resource not found. So, we will add an annotation @ResponseStatus to generate the Status: 404 Not Found.

UserNotFoundException.java

Step 6: Again move to Postman and generate a Get request.

Implementing Exception Handling- 404 Resource Not Found

We get the proper response Status: 404 Not Found when a user resource does not exist. The body of the request provided by default error handling that’s why we are getting this return status back.

Implementing Exception Handling- 404 Resource Not Found

The combination of Spring Boot and Spring Web MVC framework provides error handling. Spring Boot auto-configures some default exception handling. It is important to have a consistent exception message which is obtained for all the services inside our enterprise.

If we have a big organization and each of the services returns the exception messages in a different way, so it is not good. It would be good if we define a standard exception structure which is followed by across all the RESTful Services.


You may also like