Global Exception Handling Spring Boot with Controller advice | Exception Handling in Spring Boot

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in the description below today we are going to start with the global exception handling in spring boot so the very first question that may arise is why do you actually need exception handling in the first case so in real world i t project it is very important to handle errors correctly and simultaneously provide a meaningful error message to the clients also in the previous video we have seen how to handle the exceptions using custom exception handling where we have to use try catch and throw and throws every single time in every single class now today we are going to see how to reduce those number of lines of code and to handle those exceptions globally and this actually depends upon the project requirements if if you have different type of uh exceptions to be thrown in different controllers and they are not global exceptions which are thrown then you have to use custom exception handling but if you have a common type of exceptions being thrown in every single controller or services that you have then you can always use a global custom exception handling and how it is going to reduce the number of lines of code that we are going to see in the last part of the video so today let's get started with how to handle properly these errors specifically in spring boot and the prerequisite is just two or three things that is spring boot the crease and creation of rest apis and we have covered all these things in the previous videos if not please view the videos before this now how can you make error response clearer in spring or spring boot so we are lucky enough that spring already comes with a built-in support for error handling so till now what we have done is we used basic java java concepts try cache finally throws these particular things were actually a built-in support for java but spring also comes with built-in support for exception handling and that's where the annotations for the exception handling comes into picture now it is our job to understand and implement it so please stick with me till the end so that we can understand how these annotations actually work for us so this currently i'm not going through all these theory i'll come back once i've shown you the live demonstration first understand these four uh annotations which we are going to use during the coding part so this controller you all know we have used during the crud implementation it is a controller which is used to handle the rest operations at the right controller advice it is basically used to handle exceptions globally so remember either it controller advice the next generation which we are going to use is exception handler and a very important annotation which is not actually necessary but you can use as i did response status we are going to use it so i am going to tell you about this annotation also and also importantly remember that whenever you use the controller advice you should always extend this class response entity exception handler because it has inbuilt methods which i am going to show in next few seconds so let us get started with the line demonstration first and then we are going to come back and understand the theory behind it so if you would have remembered we have created a crud operation and this is not a custom exception handling right now so what the crud looked like before the exception handling is something like we have a post method to save we have a get method to get all the employees we had a get method to get a particular employee a delete method in an update with a simple crud simple a controller looks like this a service which was handling all these methods looked like this so it says that if you have an employee please save it if we want to get everything and if the employee list is empty we are going to throw in a business exception one of the part of the custom exception handling we see if you're going to get an id find by and delete is deleted by update and add is going to share the same method that is add employee now how are we going to convert this whole try catch exception handling customer exception handling into global exception handling so as i've told you we have not to do anything we are just going to handle it globally so i'm assuming that if you have a a client a client is going to hit your controller controller is going to hit your service and service if throws an exception comes to controller and if controller does not have a try and catch block or the exception custom exception handling then the client is like what other error is getting into it like suppose null pointer exception so what is going to get into the uh postman or the client uh console is a complete null pointed exception with where the code number line number which is not required by a client client won't understand what is actually all about so what to do in that case not to do that particular kind of exception handling causes an error so rather than writing that much line of code we are going to create another package and in that package we are going to create a global class annotated with the right controller advice and that class will be capable enough to handle our exceptions globally so whether it is service whether it is controller at the end the parent is controller so all the exceptions are required to be handled at controller level so we are going to create a package say advice simple in advice i am going to create a simple java class say my controller advice okay in that class i have to do few things i have already told you that at the rate controller advice integrate controller advice okay this controller advice is going to handle the exceptions globally it allows you to use the same exception handler now you will ask him what is exception handler so this this is a global exception handling class for me now what if a particular exception is thrown so we need to use multiple methods here which is going to handle the exception now you will ask me what kind of exception say suppose i have a class which is an employee service which is a business class now if employee the name of the employer something is null or empty i need to throw an exception and what that exception should be that the input fields are empty so if i want to put an input fields are empty i should not use a single common exception but i should create a different class for it so i am going to create a different class say empty input exception simple now my empty input exception is extending the runtime exception and it has error code and message similar to that now what i'm going to use is i'm going to copy this empty exception in my service and i'm going to throw that and i'm going to say that input fields are empty if this exception is thrown where do you think this exception is going to be handled so this is being called from controller so controller does not have try and catch so if this is thrown what will happen let me show you what will happen so let me quickly run this for you okay so suppose my id is a long value which is 2 and my name is empty okay now in this case this is a post request if i'm going to send it what will happen my controller goes here it says that yes the employee name is empty it's going to throw me an exception if i'm going to do f8 then you can see i am getting internal server error why i am going to get internal server error because my controller does not have the try and catch written here right in the add method i do not have any try and catch so that is why my console shows me an error of null because the the exception is thrown but it is not handled with try and catch that is why i need one exception handling technique either the custom exception handling or the global exception handling what i could have done i could have done something like try and catch and catch the exception here and then throw something which the uh the person or the client can understand what do you understand by this at the code save i am getting an internal server error 500 internal server why nothing is explanatory i cannot understand anything so i have already told you how to handle exceptions with custom exception handling now i am going to tell you how to handle with the global exception handling so we have used controller advice so now this is the global exception handler for us but we have to tell them that please handle one exception so it's the work of exception handler annotation which is going to tell me which exception so it's my empty what empty input exception empty input exception dot class simple so this is the annotation which is going to be used and there is going to be one method public which is going to return the response entity of type say suppose string i want a reply in a string or the message body will be string and my method can be handle empty input okay and this method is going to take nothing but empty input exceptions instance okay and what is this going to do it's simply it's going to return me a response entity right because the written type response entity to return new response entity having two things body and status so body or can be word input fields are empty right input field is empty please look into it and what can be my http status code be http status dot i the request is malformed so bad request we can say because it is a bad request getting being sent to us and at the end you have to just put semicolon if i go ahead so this is my cl annotation at the class level controller advice this is the annotation at the method level which is going to tell the method that if in controller if controller is not able to handle this exception please do not block the code please do not determinate the code but rather put some better description as a body and a proper status quo rather than 500 so currently you can say it is 500 i do not want 500 it should say that no you have sent a bad request here so this is what i am requesting the springboard to do that for me please intercept any exception handling in any controller across this project if i had 10 controllers all the 10 controllers when are going to say are not able to handle the exceptions with try catch then my controller comes into picture and it is capable enough to handle the exception which is empty input exception here so let me quickly tell you how this works so when i send it at a i do f6 exception is occurring and see my controller advice is called so before the exception is thrown and my console stands showing me an error this handler handled this exception using this dot class annotation this exception under annotation and because we have told you if in empty input exception occurs handle input empty input method should be called hence when i do f8 you can see in the body that input field is empty please look into it now can you find this more descriptive than what we used to have earlier also notice this 400 bed request so this is what we are going to get as a response when you put something empty into it now this was all about the custom exception handlers right now i have already told you that what happens if some exception occurs when existing default handler was called so this was what this is custom exception handling now suppose i am trying to call a method get now if get is being called with an employee which is does which does not exist in db what will happen so i'll give you an example let me put a debug for you first okay now i am having a get method where i am trying to find a get thing so my method is called this controller method is called with employee ids 5. where my controller goes it goes to the debug of service now here employee is 6 5 but it does not get anything so it gives me an exception so can you see this is the exception that we are getting no value present no such element exception so when no such element exception occurs then also i am getting what 500 internal server error and the status is 500 so what does the client understand with this he won't be able to understand that at the employee id 5 i am not getting anything the the return type of my this particular method is empty it's null there is no value present no such element is present so how will i let my con my client know that this is an error so again this controller comes into picture to rescue us from this exception so i am saying my exception handler and it is going to handle no search element exception now so however see this is the exception that i want to handle so exception handler will have no such element exception and dot class so by this what you are making sure that now in the controller advice whenever any controller is going to break the code like this with no value present no such element exception my controller advice is going to come into rescue will intercept that exception before that exception occurs it will see any of the exception handler matching exception 100. so suppose i haven't handled this exception yet hence my code broke now you should be always handling this exception here and put a method like here suppose i'll put a existing method here i'll modify the name so handle no such element exception will be my method and even my exception will change my exception will be no such element exception okay now it at this point of time my message should change it says that no value is present in db please change your request okay now this defines something there is no value present for employee id 5 please change your request and change your db so sorry change your employee ids which can be found in the db and the http status also changes status says what it says it's not a bad request it says that it does not exist so not found is my exception now so basically the id5 no employee is found so http status also changes here let's see if the code comes here now okay let me save this for you and let me start it again okay so initially when it was five internal server error with status 500 client was confused what hell what the hell has happened i have given the right input what what what happened at the back background so let's start again my debug goes into this my debug tries to find out now my exception handler is capable enough to intercept your exception and before anything comes on to the console and your console breaks or the 500 internal server error happens here what this interceptor did this interceptor actually intercepted your exception no such element exception it found the exception handler which is capable enough to handle this exception and it says no value is present in db please change quest and the http method will change to 404 that is not found so if i do f8 can you see that in the postman now from the status as 500 internal server error it is changed to 404 not found what we have already added here with the status 404 found and the body is now changed from 500 internal error to no value present in db please change your request simple as that so this is the power of global exception handling for you it is capable enough to handle not only your custom exception that is in the in our case it was empty input exception it is also capable enough to handle no such element exception which is a predefined default handler for the spring boot but still you have intercepted it and rather showing the 500 internal server error you are capable enough to show your client what you want to show rather than what the default exception handler wants to show in the spring boot now that was all about the global exception handling for the predefined classes with accurate controller advice i have also told you about the response entity exception handler now if you go into response entity exception handler you can see you have multiple methods say handle requires handle http request method not supported media type not supported missing several requests conversion not supported and many such methods so just by overwriting these you will be capable enough to handle or intercept any of the exceptions that are written into as a method in this class and then you don't have to think about the broken code or something the exception which is not readable by client you can always put your own implementation also by overriding these so currently if you can see that it does not have anything called as http request method not supported so suppose i am trying to like post something right i was trying to post something where input field is not empty is empty and which is a problem now if i try to put it as a get method rather than post so i am trying to call the post with a method which is going to accept a post request as a get now if i try to send it what what will happen the exception goes here in the response entity exception handler and my body is empty and says 405 method not allowed but all the clients will not be able to understand what this me what this method not is allowed is all about i want some body into it so what what does this responsibility exception handler gives you as an advantage it says that you can override me so i i can search for handle uh http uh save method not supported this last one if i try to overwrite this it it will rather the end then rather than calling the one which is already called i want that i should have a response entity of my of my type so i want that my response entity of type object should have this particular exception which says please change your media type please change your http sorry please change your http media or method type method type simple as that so once you are done with that if i save it and if i try to debug here and let's see what changes do we see here so when i try to hit it now i should not see a blank response at 405 i should rather see a particular message in the body so let me quickly hit it here i see my control does not go into the request entity exception handler here but rather into my own advice because i have overridden it and now my method is being called and it says that please change the http method type so now if i try to make it as post and now if i try to send it my controller is not called see the best part was my controller is not called but my controller device is called not for this handle method not supported but for input type the exception which is the genuine exception so now input field is empty please look into it so proper exceptions are being told to the client and now understanding these inputs the client can understand what what wrong he is doing into the inputs so that was all about the exception handling global exception handling now as discussed i am going to discuss why global exception handling and why not the custom exception handling so if you can see my global exception handling controller is just two liner code everywhere no try no catch no exception handling nothing now if i had hundreds of controllers here all the code will all these things will have only two liner codes but if you remember in the custom exception handling my controller used to have these ten lines of quotes where i'm the redundant code where you are going to it's an exception type always i'm going to always catch an exception always catch a business exception so this is the repetitive code handle the business exception handle the exception this is and if you have 100 controllers this is this is repeated 102 number of methods it's all those controllers have so all these boiler code plate codes are reduced to just two liner code here so this is the beauty of custom exa the beauty of global exception handling but now you will ask me why custom exception handling so the reason is that there might be a case that not all controllers are going to handle the same type of exception here i have a very simple crud operation hence all these controllers are handling the business exception and a common exception now suppose if you have uh employee exception suppose a database a different exception like department exception teacher exception all those are going to handle the different kinds of exceptions so there you need a different controller a different catch a different customized exception and a different message also in that case you have to use custom exception handling but if you have something which is common then i will always ask you to go with the global exception handling as the boilerplate code is terribly reduced here also my service is just one liner one single liner i do not have to think about the exceptions that are going to happen here all those exceptions that are going to happen in all my services will be handled in one class which is controller advice which is going to intercept my exception and before the console is going to throw an error before that it is going to find a particular exception handler which is a perfect exception handler for it and then it is going to use that particular exception handler as the method for your method exception handling so that was all about the reason why you are using global exception again not custom exception handling and also to why customer exception handling is also important it depends upon your project requirement if you like the content please like share and subscribe it will motivate us for creating more such videos please let me know in the comment section what next topic i should cover so that we can prioritize according to your requirements thank you
Info
Channel: Code Decode
Views: 130,577
Rating: undefined out of 5
Keywords: exception handling in spring boot, spring boot exception handling, spring boot global exception handling example, spring boot interview questions code decode, Global Exception Handling in Spring Boot, global exception handler in spring boot, global exception handling, spring boot code decode, spring boot exception handling controller advice, spring boot exception handling best practices, spring boot exception handler, spring boot exception handling code decode, code decode
Id: hLlGAQ5NfTE
Channel Id: undefined
Length: 24min 12sec (1452 seconds)
Published: Mon Apr 12 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.