Custom Exceptions in Spring Boot

Mete Aydın
2 min readOct 2, 2022

--

Sometimes we need custom exceptions in our services. For example, we must throw different exception for login or service operations. Let’s see how we can throw our own custom exception.

I’ll go through the layering parts. Because If you do research on custom exceptions, I think you might know this. :)
Before,we should create our entity.Next, we’ll create our dto’s, repository, service and controller.

If you are wondering which dependency is being used, you can examine the pom file. I didn’t add any dependency for custom exception.

We’ll create a response class for our custom esceptions. We added localDateTime, because it can be useful when we reading logs.

Now, We create our exception for use in services. We’ll extend our custom exception in RuntimeException class. Because We will encounter these errors at runtime,not compile time. We have only one variable in class. We’ll show different messages on different services.

Now we come to the most important part. We’ll create exception handler class.

Controller advice annotation allow us to write exception handlers for controllers in our application. We can catch or modify returning values of our controller methods. We’ll define exception handler for our service execution exception class.

The custom exception seems to be ready. Let’s use this now. We have to modify create method in product service.

We expect code and name fields for create a new product object. But we want code must starts with ‘A’ character. Let’s run the project and check this.

Firstly, We’ll try with the expected data.

Now, it’s time to check the custom exception. We change the code field.

It’s work! You can check the github page to review the code.

--

--