Error Handling

In this lesson, you will learn about handling errors in Spring Boot, using code examples.

What is exception handling?

Exception handling is a mechanism that handles errors. In our case, it is the mechanism to handle any errors that may occur when sending a request or receiving a response from a Spring Boot application.

Ways to handle an exception

Spring Boot provides us with various ways to handle the exception. Let’s look at a few of them.

Using ControllerAdvice and ExceptionHandler

Spring Boot automatically resolves classes annotated with ControllerAdvice and applied globally to all the controllers. These classes having methods annotated with @ExceptionHandler, are the ones that are called when an exception happens matching the exception type. Each of the exception types can be handled separately and in different ways.

In the code example, we see that the ExceptionController class is annotated with ControllerAdvice, and it has methods to handle custom exceptions the application may throw, such as PlaylistNotFoundException and SongNotFoundException. These methods handle the exceptions and return ResponseEntity<?>.

The structures of PlaylistNotFoundException and SongNotFoundException are also given in the below code example.

PlaylistNotFoundException and SongNotFoundException extend unchecked RuntimeException with a custom message.

Get hands-on with 1200+ tech skills courses.