As API developers, we all have to handle the exceptions and return meaningful responses to the client side. The old way of doing this in Java is using try-catch. The problem with try-catch is, the code may lengthy and there’s no centralized place to handle the error responses and messages.
By using the power of SpringBoot we can eliminate lengthy code lines used to handle exceptions. Handling these exceptions globally at a centralized place is called as GlobalException Handling. We can use a few annotations to achieve the goal.
@ControllerAdvice — This annotation allows us to handle exceptions across the whole application, not just to an individual controller.
@RestControllerAdvice — This is the combination of both @ControllerAdvice and @ResponseBody. Using @RestControllerAdvice is the more convenient way for handling Exception with RestfulApi. Otherwise, we have to use @ResponseBody along with the
@ExceptionHandler — This annotation is used to handle the exception. This will be used to write the Controller Advice class file. This is for determining the type of exception a method handles.
Let's move into the implementation.