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:
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.
Now, we will use these 2 classes to throw Exceptions in our code along with a proper display message.