global error handling in asp.net core web api

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey there everyone it's ravindra here back with another video in this video we are going to learn how we can handle errors globally if you find this video helpful then please hit that like button it really encouraged me to create more content if you haven't subscribed this channel you can also subscribe it so let's get started if we look at this code we are using here more traditional approach which is a try catch and here in the try block we have written these statements equals to 5c equals to A by 0 and here in this line it will throw R divide by zero error that exception will be logged here and I am using serilog so if you are interested in serilog I will put down the link in the description box let's see how we can remove this track h block and handle this error globally for that we need to create the custom exception middleware but before that let's run this code and let's see what is happening here so if I execute this code here this end point here here we will see that we are getting five double zero in response and in the document body we are getting this we are getting type title status Trace ID and if we look here that here we are getting this error message in the console because we are using a Serie log here to logging our error so we can see here the error is attempt to divide by zero it is type of error and it is coming in cell log demo.controller.personcontroller accent name is personcontroller dot get etc etc okay so let's close it for now and let's go back to the visual studio so first thing we need here first thing we will create here a model folder because we will return a strongly typed message for that we need to create a class so just type here models and inside that we will create a class so that class will be error response dot CS inside that we need to create two properties so type here prop double tap first thing will be status code okay second thing will be a string and it will return message very good now we will override to string method here so type here public string override I guess it will be public override string to string that's it and here we are not gonna return this we will return this dot sorry so we are gonna use here Json serializer Syria laser okay and it has added this statement here using system.txt.json and we will see realize whatever it will get from this object okay now we are done here so let's create a folder here and name it that folder middle base we will create here our middleware so let's rename it once more so now here we will create our middleware so just create new class here and name it exception middleware that's it okay so we are going to inherit here I middleware okay now we will type here Constructor so that we can inject something to it now what we are going to inject here we are going to inject our logger here so right here okay let's not type here just type here hi logger sit inside that we will pass the name of this class which is exception middleware okay just type here logger and here we'll type this control dot dot and here we will find this option create and assign field logger and it will create this field for us and assign this field for us but we are going to change its name so that we can distinguish these two okay so right now if we look here it is yelling at me so I will click here so potential risk sorry potential what it is saying whatever it is so I will just press here Ctrl Dot and I will Implement interface so it has implemented this method for me that very good now here we will just type A type sorry not tie try cash block okay so type here try and double tap that's good and here we will type exception that also good here we will just type next and so here we have to write a weight next and inside that we will pass this context that is good now what will happen if we go here in the catch block so we will log our error here so just gonna type here logger.log error and here we will type something went wrong so just type here something went wrong okay now here we will write some more code so now here we are going to create a private method so just type here private that tick and it will be a task and exception that's good it will take http contextp context context and one more thing it will take exception from us okay now what we will do here we will get a status code so status code equals to int status codes what it is http status sorry everything it is it is HTTP status code Dot internal server so why so let me see HTTP status code Okay so I had to add this line here system.net okay so here we are getting status code which will be five double zero so it will give us a value of five double zero that's pretty good so now what we will do here so what was our model here we will create the object of error response so just type here where error response equals to new error response okay status code equals to status code that's fine message equals to ex Dot message now we need to pass this error response to here return http sorry written context dot right context order response dot right async and here we will write error response dot to string okay but before that we need to do one more thing here we have to set the context type so here we will set context dot wrist response dot content type equals to Applications last Json Dash and here we also need to fast status code yeah it is giving me right suggestions okay so we are good now so let's call this method here so just call here await and double exception and pass this context then pass this an exception okay we are good so far so now let's create one more class here we are going to create a we are going to create an exception match sorry extension method for this middleware so here we are going to create the extension method and extension method need a static class so just name it exception middleware extension Okay so let me format this guy public static and it is a class that's why it is yelling okay we are good now so here we will create a method so just name it public void so it will also be static so here we will type public static void configure exception middle rear and this name more this name makes more sense here we will pass I application Builder app good and here we will just call app Dot middleware use middleware and inside this what we will pass we will pass this name okay so we are good so far so what we need to do here we need to go in the program.cs file so first we need to inject this okay actually why I am here okay so here in the program.cs file we need to inject this service so how we can inject it so we can simply inject it here Builder Dot add transient sorry Builder dot Services dot hair transient and here we will pass this class name exception middleware now we have injected this service now we need to call our middleware so we will call Here app dot configure and what it was app.configure exception middleware so just paste it here and if we press Ctrl Dot okay so it is fine we do not need to press Ctrl Dot configure exception middleware so calling here just right here exception Middle where okay so it looks fine so let's go here let's go here and let's comment this guy and copy these three lines here and comment these three lines okay so we are removing try catch block from here so let's run this program so here we can call this end point so let's try it out and let's execute it and our code we break here that I do not like about this Global exception Handler if I have put here the try cash block it will not break down anyway so let's move further less click on the continue and here we can see that we are getting five double zero and we are getting this status code five double zero attempt divided by zero so let's go here in our exception middleware and let's see is it even working or not okay so if I click here and let's run this guy again so here we can see we move here and here and here code will break that's it and we are getting this status code five double zero okay attempt to divide by zero so it is how our Global error handling works with custom middleware or custom exception middleware but here is a situation that in every situation we will get this status code five double zero what if I want four double zero or I want four zero one these type of 404 not found method so four zero four not found status code so how I can get those status messages here this status codes here so we need to refactor our code a little bit so that we can also get some other kind of status code here so let's close it for now and let's go here but before that we need to create our custom exceptions also because we do not have http not found exception and we do not also have bad request exception so we have to create these exception manually so here let's create another folder and let's name it acceptance exceptions and inside this we will create a class and let's name it not found exception so not found exception dot CS okay so let's inherit an exception here and here we will just call a Constructor okay and here it will be a parameterized Constructor and it will get a message and we will call a paste Constructor here and pass that message here so that's it that is more simple so let's create another exception and let's name it what we need one is not found exception and another one is bad request exception and here it is yelling at me so I have done a step spelling mistake here so now we are good we have created two exceptions here not found exception and bad request exception okay so what now this let's move here in the exception middleware let's put breakpoint here now we will use a switch statement switch exception switch ex and here we will write some case case HTTP sorry what was that let's see not found exception okay so here we will type not found exception and inside that just right here break and what we will do here what we will do here we will re-initialize it and or we will change its value here so so let's paste it here and here we will simply type int sdtp status code status code Dot something like this four zero four what it is not found yeah not found let's copy it also here and here we will use bad request exception fair enough now here we will bad request okay so that's it but we can also use another approach here because here we have to use this type casting so we have another class here which is status codes and we can type here five double zero something like that let's see what it is the status codes dot internal status five double zero internal server okay and here we will also type status codes state status codes Dot not found and here we will also write status code dot bad request now here we will use another case and it will be divided by zero exception and we do not have to create this exception because it's inbuilt one so just type here status codes the same one status four double zero bad request so you can see we can handle exceptions on the basis of status codes and here you can Define some more you can Define some more exceptions according to need okay so let's see let's call these things so let's move to the our controller and here I have this method which I have created earlier and we can see we have to refactor it so just type here Ctrl dots and it will add this line here that's fine so what we are doing here we are creating a get method which is accepting an ID and we are checking if ID equals to 1 and here we are creating or simulating or divide by zero error and in this case we are simulating the record not found or 404 not found exception and in else case we are simulating the bad request and if anything of these will not happen we will simply written ok so let's let's run this here we have this method and let's try it out and just pass one here so what is defined here if we pass one then we will reach to this section so let's pass one okay so here we have got this error attempted to divide by zero let's continue and we will go here let's move ahead so we are getting in this case which is status code sorry which is divided by zero section and let's move ahead that's fine let's continue and let's see what we are getting here so we are getting four double zero response status is four double zero and response body is this status quo four double zero attempted to divide by zero okay so let's pass here two if we pass 2 here and let's move ahead so let's see where it will go so it has gone here because it's a not found exception and here we will see that we are getting this status code 404 record does not found okay good so we have got this 404 status code let's type here anything else let's type here for and here we will go into this section pad request exception and here we can see this poor double zero bad request and we are getting the message bad request status code so that is it but when we click on this execute button our code breaks here and I don't like this but if we have deployed this thing in a server then code will not break okay anyway it is what it is so you can see it is how we can Implement Global error handling in asp.net core web apis so that's it for now I will see you next time
Info
Channel: Ravindra Devrani
Views: 2,847
Rating: undefined out of 5
Keywords:
Id: HqYUgPlGbE8
Channel Id: undefined
Length: 26min 6sec (1566 seconds)
Published: Sat Mar 18 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.