Spring Boot REST Basics : Create Custom Exceptions with @ControllerAdvice annotation
Zer
Posted on September 20, 2023
Overview
In this post, I will share my experience in creating custom exceptions with @ControllerAdvice
annotation.
Prerequisites
- Basic Spring boot knowledge
- Basic REST API / Web Dev knowledge
Custom Exceptions
In Java, we can create our own type of exception that is tailored to our business logic. Custom exceptions give us the flexibility to add more information to our exceptions and to handle errors in a different way.
ControllerAdvice annotation
The @ControllerAdvice
is an annotation that allows us to handle exceptions globally in one file. So we can just create one class and define the actions or methods that will be triggered every time an exception is thrown.
Let's get started
In this example, I want to create a custom exception that will handle login errors and return a 401 Unauthorized Error
HTTP response to the client.
1. Create your own custom exception
In creating your own custom exception, you have to make sure that your custom exception class is a child of Exception
class (checked) or RuntimeException
class (unchecked).
I created my own custom exception called CustomInvalidLoginException.java
and extend the RuntimeException
class.
public class CustomInvalidLoginException extends RuntimeException {
public CustomInvalidLoginException() {
super("INVALID LOGIN");
}
public CustomInvalidLoginException(String message) {
super(message);
}
}
2. Create your own global exception handler
In my project, I created a class called GlobalExceptionHandler.java
and annotate it with @ControllerAdvice
to let Spring boot know this is a global exception handler class.
Inside the class, I created a method that will handle the invalid login exception and annotate it with @ExceptionHandler(CustomInvalidLoginException.class)
.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomInvalidLoginException.class)
public ResponseEntity<Object> handleInvalidLogin() {
return new ResponseEntity<>("INVALID LOGIN", new HttpHeaders(), HttpStatus.UNAUTHORIZED);
}
}
For this exception, I will just return 401 HTTP status
to the user.
3. Test
Lastly, all you need to do is throw the custom error in your business logic.
...
else {
throw new CustomInvalidLoginException();
}
...
Conclusion
Spring boot makes it easier for us to manage exceptions just by using these annotations: @ControllerAdvice
and @ExceptionHandler
. In my opinion, this improves the readability and maintainability of your application because you can handle your exceptions in just one file!
Posted on September 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 20, 2023