Handle Exceptions (Exception Handling) in Spring Boot REST APIs (Part 2)

Prabhu Kumar
3 min readMar 12, 2021

--

In this post we will see how to handle exceptions for User Restful API I have created in my earlier post using spring boot

Spring Annotations

Let’s look at two Spring annotations that we will use to handle exceptions:

@ControllerAdvice

@ExceptionHandler

ControllerAdvice

The @ControllerAdvice annotation handles exceptions globally — it allows you to use the same ExceptionHandler for multiple controllers. This way, we can define an exception handler in just one place and this handler will be called whenever the exception is thrown from classes that are covered by ControllerAdvice.

ExceptionHandler

The @ExceptionHandler is an annotation used to handle exceptions thrown during the execution and send custom responses to the client.

The most common way to use @ExceptionHandler is on methods of @ControllerAdvice classes so that the exception handling is applied globally.

The steps to handle exceptions in spring boot applications are as below.

Create the application exception

In our User Restful API, create the application exception named UserNotFoundException which will be thrown when a specific user with the given ID is not present in the database as shown below.

Raise the application exception from the UserService class

When retrieving a specific user for the given ID, if the user is not present in the database corresponding to the given ID then raise the above application exception named UserNotFoundException as shown below.

Handle the application exception using global exception handler

Create a global exception handler class and annotate it with @ControllerAdvice as shown below

Create a method for each application exception and annotate it with @ExceptionHandler as shown below. And return the ResponseEntity by passing the custom Error Response and Http Status Code from the above method.

Test with Postman

Get user By ID (Successful Scenario)

Get user By ID (Exceptional Scenario)

That concludes how to handle exceptions in spring boot REST APIs. If you like this tutorial please give a clap.

--

--

Prabhu Kumar
Prabhu Kumar

No responses yet