ASP.NET Core 8 - Exception handlers (goodbye error handling middlewares)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in most Web projects exception handling is usually done by either using a middleware or by using filters or by using libraries such as mediator we could do it using pipeline behaviors however now inate we have a new interface for this purpose which is able to register exception handlers and you can also use the built-in mare to handle exceptions in a more graceful way in this video we'll see how can we use this new feature in an example web API project so here I have some example. net a web API project and currently to handle exceptions it is using actually a custom mid so if I go to the a handling mid class you can see that we are just basically having a big TR catch block with each error type defined in the TR catch and depending on the type that we are actually catching we'll return a given status code and also write a message to our API client in the case that any of those exceptions are en catched we have this very generic exception that is just returning 500 and something with the wrong information to our API client in this project I have also two example Min my AP AP standpoints that first of them is actually throwing a generic exception and the second one is throwing more specific one which is not found exception so let's go ahead and try to execute both of them and let's see what will be the response going back to our client so in the first case when I'm throwing the generic exception if I just let the current error handling mare to execute we'll see that we get a 500 internal server error and the message something went wrong as you just seen in the implementation class but if I execute the endpoint that throws not fin exception well in this case if I just let the program to continue we'll see that now we get four or four not final exception so having this custom implemented and used in our web API project as you can see we are returning different status codes to our web API client depending on the error draw in the application so maybe let's try go ahead and rewrite this feature using this new ey exception handlers so first of all I'll just comment out the US M that we used previously and maybe let's go ahead and create a new class I just call it maybe app exception Handler and this class should implement the I exception Handler interface and its only method to implement is the try handle lasing method its three parameters are of course the HTTP context from which we can get the information about the incoming request we can also write to the response and set the status code then the second parameter is of course the exception that is thrown during the wepi request processing and we also have cancellation token in case it's needed so as this class is going to be registered in the dependence injection container you can also utilize The Constructor to actually inject any type of references but for the sake of this demonstration I will just use the ilogger interface and create a private field for this type of reference so now in the try hand lasting method if I wanted to actually replace the existing midle well I could do it like this for example using the switch expression we could check that exception is type of forbit exception and for that case I will just go ahead and return a tle of a 403 status code and no error message so maybe let's just Define a tle with two values so the first one will be int status code and the second one will be string error message all right so having this two defined maybe let's go ahead and cover the rest of the cases so the exception type B request exception would return 400 status code and the error message from aone exception then in the next case I'll just handle not found exception which returning 404 and returning the message from our switch and besides those three I would also handle the default case so for any type of exception that is not one of them in that case I'll just return 500 and something with wrong information so now having the stuple defined from the S expression we can just go ahead and use the HTTP context response and set the status code to the value that is coming back from our s expression and now to write the message to our client again you could could go ahead and use the response and with the and with the write as Json I think we can just pass in the error message coming back from our tle and as this is a synchronous method I will have to await it and make the whole method declaration to be a synchronous with the snc keyword and maybe before that I could also go ahead and use the logger so I'll just log the exception and maybe the error message so right now you might wonder what should the return from this try handling method as the return type is defined to be value task of a Boolean so basically we'll have to return a value of true or false and true would mean that the exception is properly handled and there is no need to go ahead and search for another exception handlers you can just stop the error handling in that place but if you would return false value from this try handle method that would mean that the middleware that is actually handling the exception with our custom exception handler classes it would try to go ahead and find the next implementation of the I exception Handler interface to actually handle the throne exception so as long as the reg exception handlers will not return a true from the try Handler sync it will just keep on going and executing the next implementation of the tri Handler sync method maybe to demonstrate that behavior in a minute We'll add a separate exception Handler but right now I'll just return true and this will mean that we are done with the exception handling there's no need to actually process any further okay so having this class defined we'll have to go back to the program Cs and now we'll have to register that but to register s interface I will not use adcope I use add Trent I use a special dedicated method which is ADD exception Handler of a generic type for our app exception hander like this and having this exception Handler registered you can use the exception Handler middleware which has been already existing inet for more than eight years and for now it's been used mostly by MVC application or razor Pages application to actually map a certain page or a certain URL to be used to handle exceptions and the user of the application would be redirected to such URL in case of an exception thrown during the request but in our case we don't have to redirect the user so I just use it without any parameter but with this implementation if I go ahead and start the web API project and try to execute one of those two minimal API send points well as you can see we are getting an exception but this is of course not our exception it's just saying that we'll have to set the exception handling puff or the exception handling property in order for the exception Handler mware to use properly and for now this actually a known back and Microsoft currently suggest to do a small work around which is passing a empty Lambda with a configuration and with this implementation now the exception handle middleware just works fine so again let's go ahead and throw some Exception by the throw minimal end point and as you can see we are drawing the exception maybe let's go ahead and put a braak point in this try hand lasting method and if I click continue we of course hitting this break point and right now as this exception is just a generic one we will be returning 500 and some error message something went wrong so the client of our API is getting the 500 internal server error and something went wrong as the information back but if I true not fin exception well in this case again in the switch statement we are now returning four four and some error message from this exception and this will mean that the client is going to get 404 not found exception and the message from the exception Throne so in this way having our custom exception handle class defined and used with the existing exception handle midare we are able to actually handle exception without the need of having to define a tri catch block because this is actually done through the existing middleware all right and maybe just to demonstrate I will go ahead and try to remove this default case from the switch statement and in that scenario I'll just go ahead and return a default tle so if we would check that the for example status code is equal to default value in that case I would just return false and this would mean that the exception is not properly handled and the exception hand Handler mware would try to go ahead and find a second registered exception Handler and execute its try handling method so of course right now we need a second Handler so maybe let's call it General exception Handler and of course this class would also implement the I exception Handler interface so as you already know we can just use the Constructor to inject any kind of reference to this class so maybe again let's go ahead and use the ey logger for the type General exception Handler and for this reference we'll just go ahead and create a private field all right so now in the tryand lasting method I just use the logger and then maybe instead of returning 500 I'll just go ahead and return 501 just to make sure that we are actually returning status code from with the second exception Handler and the client will just return message something went wrong and finally we can just return true and this will mean that the exception is properly handled so right now we'll have to go back again to our program and register this new general exception Handler so again using the add exception Handler method I can just register that by using the type definition so let's go ahead and run the program again and right now if I drew the not exception it should be handled by our app exception Handler so let's actually go ahead and try to execute such endpoint as you can see we are going to the first custom exception Handler and as we found not fin exception well in that case it will just return four or four and some error message to the client and just return true and this would mean but even if I try to set up a break point in the second exception Handler well the flow will not go here because the request is ended and now our client has the information about the 404 not found as some message returned to the user but if we threw a generic exception well in this case we'll try to handle that in our app exception Handler but as this is a default case which is not handled in this class will just return false and this would mean that the exception handled mider is going to execute the next one in the loop which is in our case General exception Handler and actually this one is going to properly handle this exception returning True Value and writing back to the client 501 and something went wrong message so as you can see now the client got 501 coming back from our second custom exception filter but if you want to register more than one exception Handler it is crucial to actually register them in a correct order because in this change order right now if any type of exception is thrown it will go to the general exception Handler and it will never get to the app exception Handler to make sure I'll just start the API with this implementation so that General exception Handler is the first one to be registered and if I execute that thr not found minimal endpoint even though it should go to the app exception Handler it will go through the general exception Handler first and here as we are returning through value it will not go any further and the client will get the message 501 not implemented and something went wrong so it is very important to actually make sure to register the custom exception handlers in the correct order just like we do register midle work
Info
Channel: Fullstack Dev
Views: 14,787
Rating: undefined out of 5
Keywords: c#, .net, .net core, c sharp, from scratch, visual studio, .net cli, cli, tutorial, free, coding, programming
Id: f4zMGR3m70Y
Channel Id: undefined
Length: 11min 0sec (660 seconds)
Published: Thu Nov 23 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.