Exception Handling II
Learn how a global exception handler works.
We'll cover the following...
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.
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
.
We will create a new class PlayerExceptionHandler
, and annotate it with the ...