top of page
image 82.png

Exception Handling

Handling Exceptions and Errors in APIs and sending the proper message to the client is really essential in a good enterprise application.

There are a few annotations used for Exception Handling:

  • Controller Advice: The @ControllerAdvice is an annotation, to handle the exceptions globally.

  • Exception Handler: The @ExceptionHandler annotation is used to handle the specific exceptions and send the custom responses to the client.

We need to define a class named CustomException that extends RuntimeException:

image 65 (1).png

Then, we need to create another class named ExceptionHandlerController which will annotate @ControllerAdvice to handle exception globally. We can define any Exception Handler methods in this class file.

image 65 (2).png

Now, we will use these 2 classes to throw Exceptions in our code along with a proper display message.

image 65 (3).png
bottom of page