Exception Handling in Spring Boot REST API Explained With Demonstration

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
detailed demand so controller advice response entity 404 hello everyone very warm welcome to think constructive i am isha in this session i will be discussing exception handling for rest api spring boot project this will be a detailed discussion for custom exception handling for rest api spring boot project so if you are planning to start working with rest api spring boot or you are already working on rest api spring boot project the session is going to be extremely useful for you because here you will learn how to do custom exception handling for any spring boot project okay in this session i will start with the quick discussion of exception handling and that will be followed by the detailed demonstration of custom exception handling all right so let us start with the discussion now so what do we understand from the term exception handling exception handling is to handle any exceptions or any errors which occurs in our application so whatever application we are building exceptions has to be handled in that application properly so exception handling is a must have feature for building any application even if you are building a small application or you are building a large application so goes with rest apis so when we talk about apis any good api must have exceptions handled properly so that it can give a proper response back to the client whenever that particular apis are called by the client and if there is any problem occurs in that api call due to any reason api should return a proper response back to the client so that client is well informed that there is some error or some problem has occurred responses should not be misleading or abrupt all right so these are the two main annotations we will be using in today's demonstration these will help us to do the custom exception handling in our springboard rest api project okay so first one is the controller advice so controller advice annotation is used to globally handle all the exceptions all right so it applies globally to all the controllers and whenever wherever any exception occurs this controller advice will be able to handle it so this is one annotation we will be using another annotation is exception handler exception handler annotation handles specific exceptions and send custom responses back to the client that means a proper response whichever we want to write and whichever we think that client should be able to understand why that problem has occurred those customs responses will be coded with the help of exception handler annotation all right let's switch to the demonstration and we will see how we can do the custom exception handling in our rest api spring boot project okay here is the intellij idea editor you can use any java editor of your choice all right so i have opened my res demo application which we have built in our previous sessions so i'll just give you a quick recap of whatever we have built till now and i would highly recommend you to watch the previous two sessions so that you can connect and understand fully everything and going forward i will be including more stuffs in this application in my subsequent sessions please follow along all the sessions of springboard these sessions are going to be extremely helpful for you all right so what we have built in our previous sessions we have built our controller layer for a spring boot rest api project so here is the controller package and in this you can see cloud vendor controller is already created in this what we have done we have created our get request get by vendor id then get all cloud vendor details followed by creating cloud vendor details updating cloud vendor details and finally deletion of cloud vendor detail by id here is a cloud vendor model with four properties vendor id vendor name vendor address and vendor phone number okay these are the four properties of cloud vendor class and in the database the table name cloud vendor info will be created will be having these four properties okay so data will be saved in cloud vendor info table which is created in our mysql database then we have repository layer repository layer is responsible to interact with the database with the help of jpa repository this cloud vendor repository is extending jpa repository all right which is having cloud vendor entity and the id field as a string so this jpa repository is responsible to interact with mysql database for saving data of cloud vendor and retrieving data of cloud vendor okay then we have service layer which is having one cloud vendor service interface in this cloud vendor service interface we have declared five methods for creating updating deleting fetching and fetch all cloud vendor details okay and then further we have service impeller that is implementation of this service interface that is cloud vendor service impulse in this we have implemented all these five methods which we have declared in this service interface all right so you can see cloud vendor service simple is extending cloud vendor service okay so all five methods are implemented here fine and then we have a quick look at our application.yml file in this file we have done the configuration related to mysql database okay so this is a quick recap of what we have built till now i'll just quickly bring up the application and show you one scenario and then we will proceed with the exception handling stuff so let us now bring up the rest of our application and see what happens so my application you can see here in the logs it is started okay i will now open mysql workbench and will show you the table first and then i will open postman and trigger a request okay so here is a mysql workbench you can see cloud vendor schema is here okay and inside tables cloud vendor info table is existing i just say select rows from this table what i am getting right now the entire table is empty blank why because i have just now started the application so this table is freshly created that means this this table currently doesn't have any data okay so we have just now seen there is no cloud vendor existing in our cloud vendor input table okay because the table is blank as of now so let us try to query get by id now so i would want to query or fetch the data for the c3 vendor okay let's see what happens same what i have got is timestamp status as 500 error message has internal server error and this the path okay and here also you can notice i am getting 500 internal server error that means something bad has happened and my query did not work but really whether i am able to understand from this message what wrong has happened no right but i will assume okay some server error has happened but i really don't know so how to fix this kind of problem that means how to get a proper error message with a proper status response here that actually what problem has happened so that the client can understand that there is some problem has happened and that problem has to be sorted out so until unless the client will get that proper error message the client won't be able to understand what problem has happened so in order to give this kind of proper client friendly message and a status we should be doing exception handling that means i should be doing some kind of exception handling in this get by id method so that it can return a proper error message proper response back to the client let's say in this scenario it should have been given that requested cloud vendor details does not exist the moment client sees this message the client will be able to understand that okay cloud vendor which he is looking for which the client is looking for does not exist in okay so i am back to my demo application first thing i will terminate the application okay and here we can see controller model repository and service packages are existing yeah just one more thing in the description box below i have given the github link so you can take the code from there as well okay okay so let's first create the exception class here how will i do that i will create exception package and inside this i will create exception class okay so in our case i will say cloud vendor not found exception okay this is what i want so this is the exception i want to create the first thing i will be creating cloud vendor not found exception since my project is getting synced up with it i will just like to add my file there okay now this exception class first thing should extend runtime exception okay so that it can be recognized as exception class okay next thing i'll just create constructor for this class so i'll just say generate constructor which one i would want to generate two constructors for demonstration purpose runtime exception message string and runtime exception with message and cause okay so i have created two constructors here cloud vendor not found exception with argument as message and another constructor is with message and calls because the data type has throwable so this is the step one we should be creating the specific exception class which should extend runtime exception like this okay now the next step is we should create the exception class in which the entire exception details will be filled in and passed back to the client okay so i will say cloud vendor exception okay again i will add this to the github so let's start adding the properties to this this class so private final string what message we want to pass back to client will be given here okay then next property i would want to have private final travel this is for cause okay the next one http status all right now let us create constructor for this so i'll just say generate constructor with all three things okay let me just do a bit of repositioning okay constructor is created for this class and now i will generate the getters for this class okay getters for all three beats again a bit of a repositionings are needed let me just fix it okay so we have created cloud vendor exception class okay these are the three properties message throwable and http status here is a constructor for this sorry here is a constructor for this and then the getters for all these three properties all right so this is the second step third step is to add the handler to handle these exceptions so i'll be adding it here itself i will say cloud vendor exception handle okay you can call it cloud vendor exception controller also so both are fine whichever name you would want to give okay so i have added it to my git wrapper so you can take my gate repo code link is given in the description box below all right so now we will add a handler method in this cloud vendor exception handler okay which will be handling my cloud vendor not found exception okay so i'll be creating a public handler here okay public it should be returning response entity okay of object type and then i will say handle cloud vendor not pound exception all right and this will have the argument as i'll just shift it to next line and this handle cloud vendor not found exception method will have cloud vendor not found exception which we have created in our step one okay so these are the arguments so cloud vendor not found exception is given as an argument inside handle cloud vendor not bound exception method okay and here the implementation for this method will go fine so in this method two important things we will be doing we will be creating the payload which will be returned back in terms of this response entity and that error message or that exception message will be given back to client okay i'll explain you the flow so first thing what we should be doing we should be creating the payload here and what is my payload and where does my payload will go it will go inside cloud vendor exception okay so what i'll do i'll just instantiate cloud vendor exception okay new cloud vendor exception and inside this constructor what we should be doing we should be passing three things okay what are the three things first one is cloud vendor not found exception dot get message that means whatever message we want to give back to the client will come here okay then if we want to return back the cause so it will be cloud vendor not found exception dot get pause okay and then and last argument is http status so whichever http status we think will be more suitable we should be returning that back so http status let's say not found i want to give okay what we have done we have created a payload of cloud vendor exception which should finally be returned back with the help of response entities so next thing will be what we'll be doing we will be returning new response entity okay and inside this what we'll be doing it will have two arguments the first one is the payload which we have just now created cloud vendor exception and and the next one is http status let's say here also i want to say not found because finally the issue is the error is cloud vendor is not found so the same http status we should be returning okay i am giving it here at two places i will show you where these two things will be displayed back to the client all right so we have created cloud vendor exception handler in which we have a method called handle cloud vendor not found exception okay and we have implemented this method like this all right so the next thing is what we should be doing we should be telling this method which all exception it's going to handle okay so how do we do that we will put the annotation let me just give a line here yeah how do we do that we will put an annotation exception handler annotation okay and this exception handler will have a value as the list of exceptions which will be handled by this method okay so in our case we are handling only one exception here so i'll be giving cloud vendor not bound exception dot class suppose i want this method to handle in the same way one more exception so with the comma i can give that one more exception class here also okay for now this is sufficient so what will happen this cloud vendor not found exception will be mapped with this method argument handle cloud vendor not bound exception and the remaining things will take place like this okay i hope this part is very clear one more thing we should be doing in this handler we should annotate cloud vendor exception handle class with controller advice why are we putting this controller advice here because this controller advises responsible to handle exceptions rather multiple exceptions globally throughout this project okay so whatever exceptions we want we can keep writing the handler methods inside this create a mapping with the help of exception handlers like this and all will be intercepted or handled by this controller advice okay so that is a step number three now the next step is we need to see from where we can throw these exceptions and how will they behave okay so what we do in this service package because the service implementation is responsible to handle all the business logic okay so what we'll be doing we'll go inside our get cloud vendor method because get by id we have seen we were doing and what were we getting we were getting here some internal error okay so we want to show a better message here we'll see where should we put that logic whatever business logic will be we are doing in our spring boot rest api project that should go in our service layer okay so in this service layer what we have done currently we have just directly returned find by id dot get okay what this find by id is doing it is fetching the details from the database for this cloud vendor id and whatever response it is getting it is giving back here okay so now in this response what we are doing we are just saying get so that we can extract the cloud vendor object specifically and can return it back fine but what happens when it doesn't find any cloud vendor result or any record bag this get will throw the exception and we get the generic internal server error message okay so what we should be doing we will be putting our exception handling thing here that means i'm just going to put a check from this call if i'm getting nothing that means if this call is empty okay what will i do so if i am getting nothing from this call that means it is empty i should be showing the exception from here itself which exception through new which exception we have created we have created cloud vendor not found exception okay and in this exception i should be giving a user friendly message that is very important okay so i'll be giving let's say requested cloud vendor does not exist okay and termite so terminated with semicolon so what is hap what will happen now the moment this query will happen and it will find it is empty that means nothing is getting returned from here it will immediately throw new cloud vendor exception and actually the user will get to see this requested cloud vendor does not exist a proper error message and with this the client will know okay the cloud vendor which i am querying doesn't exist in the database fine and let's say if it exists it will simply return a graceful cloud vendor details back to the client all right got it so these many changes we should be doing now let us start our application so my application is up i have got the started resident application message okay and now let us go back to postman and see what happens so here is the postman the same get query c3 earlier we have got a status as 400 and error message as internal server error now when i will query let's see what we get good thing yeah we have got the message as requested cloud vendor does not exist my http status has not found and here also you can see for not for not found a proper error message with a proper error response the client has received all right so this is how you should be doing exception handling with your springboard rest api application okay so i hope this session is clear and now you will be able to do a proper custom exception handling in your rest api springboard project if you have any doubts please ask your doubts in the comment section below i will try to get back to you to reply to you to solve your doubts as soon as possible let's have a quick recap of what we have covered in today's session so we started with our cloud vendor rest api spring boot application okay and in that application we have added exception handling the custom exception handling so we started with by seeing the actual problem if we don't do any exception handling what kind of you know problems are there and in order to fix those problems to solve those problems how should we be doing the custom exception handling in our rest api spring boot project for that what we have done we have added this exception package in that exception package we followed three steps so first thing what we have done we created cloud vendor not found exception followed by cloud vendor exception class and then finally we created cloud vendor exception handler this one okay after adding all these three classes what we have done we went back to our service layer implementation and in our service implementation class we have put a check that if the cloud vendor does not exist how to throw the particular exception with the specific or user friendly response message back to the client all right so sprint gives us a lot in lots of features library packages we should know how to use them more effectively and you know make our applications a lot better all right so i hope this session helped you and actually you were able to learn custom exception handling in a proper way in rest api spring boot application if you have any questions please ask your questions in the comment section below and also i would like to request you to annotate the particular timeline which you feel will be helpful for more and more people and you found it really beneficial annotate that timeline that will be really helping all of us as a community thank you everyone for watching the session i hope you found it useful there are more sessions available on the channel so feel free to explore them if you haven't yet subscribed to the channel please subscribe to the channel and also ring the notification bell so that you are always updated with the new upcoming sessions also share the channel details with more and more of your friends and colleagues so that we we grow together more stronger as a community all right stay connected we think constructive see you in the next session bye for now [Music]
Info
Channel: Think Constructive
Views: 28,828
Rating: undefined out of 5
Keywords: exception handling in spring boot, custom exception handling in spring boot, exception handling, global exception handling in spring boot, how to add custom exception handling in spring boot, spring boot, spring boot exception handler, spring boot exception handling, spring boot global exception handling example, spring exception handling, think constructive, esha puri, java, java spring boot, controlleradvice, spring framework, exception handling in spring boot rest api, exceptions
Id: L2o485T70Do
Channel Id: undefined
Length: 28min 5sec (1685 seconds)
Published: Tue Aug 16 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.