Handle Exceptions in SpingBoot REST API
Hello everyone! Doing well in covid situations? I hope so...Today I brought you a very important article that will be useful while implementing REST APIs or Micro Services with SpringBoot.
As we know handling errors/exceptions in applications is very critical. In case of any failure, we have to inform about the anomaly to the user. Otherwise, if we just say it is an "error", it's not going to be a help for anyone! We have to communicate why that error occurs and what was the root cause. Then troubleshooting or bug fixing will be more efficient than we think.
So, basically, I will be creating a REST API using SpringBoot to demonstrate how to catch exceptions thrown from your service layer. This API will follow the following structure.
- controllers - which accept the client requests
- models - which contains entity classes/POJOs
- services - which performs the logic to return data
- repositories - which handles data with database
- exceptions - which holds custom exception classes
Controller Layer
The controller is the main contact point for the client application. This is the place where we should communicate the response to the client(front-end). I have implemented the logic by auto wiring the service and using ResponseEntity class. API calling path is /api/products/id. Look at the below code.
Service Layer
Here we implement the logic usually to get data. So, what we should do, when the product is not found by ID? That's the case! We can throw an exception. It can be just a RuntimeException. But it's better to have a custom exception for this use case. In the next part, we will create that. The custom exception I'm using is ProductNotFoundException. Here, I have given the code for the service layer logic. ProdcutService is the interface and ProductServiceImpl has the implementation. ProductRepository is the DAO class that helps us the connect with database. I'm using a MongoDB database.
Exception Layer
Create Custom Exception
@ResponseStatus(HttpStatus.NOT_FOUND)
Throw Exceptions to the Controller
- We are going to implement a separate Java class for this. Let's call it as DefaultExceptionHandler. This will be the global point for our exception-handling part.
- Like we use @RequestMapping annotation, we have to put this annotation at the top of the class name.
- Since we are sending the response from the controller wrapped as ResponseEntity objects, we need to inherit this exception handler class from ResponseEntityExceptionHandler.
- We need a POJO for the error message also. I have created that as ErrorMessage.
- message
- request method
- request path
- port
11 Comments
Thank you so much for this nice valuable information.
ReplyDeleteNice to hear :D
DeleteIf you're looking for the best Dell service center in Indirapuram, Ghaziabad, then you've come to the right place. This service center is able to fix a variety of laptop problems, including flickering, white screens, and more. In addition, they can help you upgrade your system for a fraction of the cost of a new Dell. If you have any questions about the service center, contact them by phone at 7042640351
ReplyDeleteDell Service Center Indirapuram
thank you for this valuable information. keep posting more.. waiting for more updates.
ReplyDeleteFind pdf | pdf search engine
There is great insight in your post. Why don't you check these out too:
ReplyDeleteHow to Remove Mintnav from Android Phone
Remove Mintnav from Android Phone
Truly African
Loopsie Android
Netnaija Movie Downloader App
plz go through this website
ReplyDeletePlease share a code of a best forum section. I want to use it for my website.
ReplyDeleteGet top-notch Law assignment help from qualified experts. We offer personalized support to enhance your understanding and improve your grades in legal coursework.
ReplyDeleteI'm not into codes but, you explained it well/.
ReplyDeleteAqualine Steel Rainwater Tanks
Welcome to 1xbet – your trusted gateway to 1xBet’s world of gaming and entertainment. We provide a seamless, secure login experience for users to access live sports, casino games, and global events with ease.
ReplyDeleteSatsport is your ultimate destination for cutting-edge sports insights and services in India. Offering a seamless platform for sports enthusiasts, we specialize in delivering real-time updates, secure transactions, and an unmatched user experience. Discover the best of sports engagement with Satsports today!"
ReplyDelete