Introduction
The @ControllerAdvice enables you to handle errors in a single place. This post will show you how to implement the @ControllerAdvice to help you with exception handling inside a Spring application.
ControllerAdvice example
The following example shows a class annotated with the Spring @ControllerAdvice annotation, meaning that it is used to handle exceptions.
The class contains two methods annotated with @ExceptionHandler annotations that define how to handle specific exceptions thrown by controllers.
| |
The first method in the example is executed when an UnsupportedOperationException occurs.
The second method has an @ExceptionHandler with an array of exception classes as input. Doing so you can handle multiple kinds of exceptions with a single method. The second method is executed when a NotFoundException or NullPointerException has happened.
Controller to test the ControllerAdvice
To try out the previous example, you can use the following RestController. The controller has three endpoints
that will trigger the ExceptionHandlers in the class with the @ControllerAdvice annotation.
| |
Conclusion
In this post, we have seen an example of how to implement @ControllerAdvice to handle a specific exception or multiple kinds of exceptions.
Bring Hands-On Modern Java Training to Your Engineering Team
Want to level up your team on Java Virtual Threads & Concurrency, Project Panama (FFM API) & High-Performance I/O, or Modern Testing in Java? I deliver intensive 1-day workshops customized to your company's tech stack and production challenges.
Want More Deep-Dive JVM Benchmarks & Project Panama Research?
Follow my weekly engineering posts on LinkedIn, explore the full JMH benchmark suites and pure-Java Linux io_uring / FUSE projects on GitHub, or download my conference talk slides: