Spring boot - handle Rest APIs exceptions using Controller advice

Rida kaddir
Towards Dev
Published in
2 min readJan 5, 2022

--

This is bad :(

Hello folks, in this post i’ll be sharing with you how i manage my Rest APIs exceptions (errors) using Controller Advice

Controller Advice?
Any class annotated with @ControllerAdvice becomes a controller-advice that support three types of methods: Model enhancement methods, Binder initialization methods and Exception handling methods BlaBla…
Don’t worry we will see an example of a controller advice with exception handling methods

Let’s get started:

To demonstrate how Controller Advice works, i’ll be creating a simple rest API endpoint.

First let’s create a basic GET endpoint that search for an Employee by his ID.
the purpose of this endpoint is to use an exception handling method to deal with the scenario when a client tries to retrieve Employee details using and ID that doesn’t exist in the database.
I used filter method from stream API to search for an Employee by ID, then i used findFirst() method that returns an Optional.

Now that we have an Optional, we can call many new methods to handle different scenarios. in our case throw a Business Exception (line 12). EmployeeNotFoundException

To keep a consistency over my application, i have a shared Abstract Class Exception that drive how each Business Exception should be thrown.
Any business exception should extend my abstract class”

Now, since all my business exceptions extends my BusinessAbstractException, i can use my abstract exception to intercept any thrown sub exception using a Controller Advice.

In this Controller Advice class we have our handleException method that takes as parameter the exception we want to intercept (BusinessAbstractException),and return the appropriate response to the Rest api caller using ResponseEntity.

A controller advice can contain multiple exception handlers - but i don’t recommend that, or at least they should be related somehow.
Finally, to make sure the team is following the rule “all business exceptions should extend the abstract business exception class”, tools like https://www.archunit.org/ can be used.

--

--