...

/

Exception Handling II

Exception Handling II

Learn how a global exception handler works.

In the last lesson, we created an error response class, PlayerErrorResponse, containing information that we want to send to the client. We also created a custom exception class, PlayerNotFoundException. The REST service throws exceptions of this class when a player record is not found in the database.

@ControllerAdvice

A best practice in exception handling is to have centralized exception handlers that can be used by all controllers in the REST API. Since exception handling is a cross-cutting concern, Spring provides the @ControllerAdvice annotation. This annotation intercepts requests going to the controller and responses coming from controllers.

@ControllerAdvice annotation
@ControllerAdvice annotation

The @ControllerAdvice annotation can be used as an interceptor of exceptions thrown by methods annotated with @RequestMapping or any of its shortcut annotations. The exception handling logic is contained in the global exception handler which handles all exceptions thrown by the PlayerController.

Custom error response
Custom error response

We will create a new class PlayerExceptionHandler, and annotate it with the @ControllerAdvice annotation so it can act as a global exception handler.

@ControllerAdvice
public class PlayerExceptionHandler {
}
PlayerExceptionHandler class

This class will have methods to handle different types of exceptions. We will write a handler ...