Global Error Handling in ASP.NET Core Web API

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
exception handling help us deal with unforeseen errors that could potentially appear in our code to handle exceptions we can use the try-catch block as well as the finally keyword to clean up our resources after the execution of the block even though there is nothing wrong with this approach we can extract all the exception handling logic in a single centralized place by doing that we can make our code more readable and the exception handling logic more maintainable in this video we're gonna handle errors by using a try-catch block first and after that by using a built-in middleware and our cast the middleware that handles are exceptions on a global level we are doing this to demonstrate the benefits of handling exceptions globally to get the source code for our starting project you can visit the global error handling article on our site the link to the article is in the description below so let's start the application by opening the various controller in the starting project in this controller there is single guide method and an injected logger service it's a common practice to include the log messages while handling errors and for that reason we created a logger manager service it logs all the messages to the seed drive but you can set that by modifying the path in the analog config file if you want to read more on how to use an log in dotnet core you can visit log in with analog article on our site you can find a link to the article in the description as well now let's start with the action modification the first thing we're gonna do is adding a try-catch block inside the try block we login info message and return students from the data manager class this class is just local storage to simulate the database finally we log an additional info message with the student's count and return our date of course we have to modify the cache block as well let's login error message and return the 500 status code with the internal server error message now we can start our application and test the result in postman let's press the send button and we get 200 okay status code and we can see our date will create the log files for this application so let's examine them and from what you can see everything works as expected now let's get back to our code and force an exception right below the gate to students method call by throwing a new exception with a custom message with this in place we're going to start our application again and send the same request there we go we can see the error message and of course let's inspect the log file there it is you can see the error message log here as well so this will is just fine but the downside of this approach is that we need to repeat our try-catch blocks in all the actions in which we want to catch on handler exceptions well there is the better approach to do that by using the use exception handler middleware it's a built in wheel where we can use to handle exceptions so let's dive into the code to see this middleware in action first we're gonna add a new class error details in the models folder this class has two properties the status code the message and the overridden to string method which uses JSON converter to serialize the object we're going to use this class for setting the error details next let's create a new folder called extensions and a new static class exception middleware extensions which we're gonna modify first we create an extension configure exception handler method with the I application builder and I log the manager parameters and with the registered use exception handler middleware by using the run method from the app error object we register the context object and populate the status code with internal server error value from the HTTP status code enumeration and finally populate the content type of our response then we extract the exception handler feature into the context future variable by using the I exception handler future interface if it's not now we log the error message by using quantex feature dot error property and finally returned the response with a custom created error details object of course we have to populate the status code and the message properties to be able to use this extension method let's modify the configure method inside the startup class with all these in place we are safe to remove the try-catch block from our action and there we go our action method is much cleaner now and what's more important we can reuse this functionality to write more readable actions in the future now we can inspect the result by sending the same request from postman there it is our stateís code and if you check our log file we can see the error message there so we just saw the built in middleware in action but now we're going to use custom middleware to achieve the same thing let's create a new folder named custom exception middleware and the new exception middleware class so we create two private read-only variables the requests delegate next and ilogger manager logger then we registered them through the dependency injection the next parameter of the request delegate type is a function delegate that can process our HTTP requests after that we created the invoke ASIC method with the HTTP context parameter this method is essential for the request delegate type because it can process requests without it if everything goes well the next delegate carries the request and the get action in the controller generates a successful response but if it's not successful and it's not gonna be because we are forcing an exception our middle one will set off the catch block and call the handle exception async method so let's create that method inside it we set up the response content-type the states code with the well-known animation value and write a response in async manner we assign the value for the status code property and the message property as well now let's modify our exception middleware extensions class with another static method to register our exception maneuver finally they choose it in the configure method in the starter plus great now let's inspect the result again there you go we get the custom middleware message so as you can see we implemented custom middleware in a couple of steps let's sum everything up you learned how to handle errors in more sophisticated and cleaner way the code is much more readable and our exception handling logic is now reusable for the entire project if you like this video you would HIGHLY appreciate you hit those like and subscribe buttons down there of course don't forget to visit the code maze blog to download the source code if you like what you see you can subscribe to our mailing list to get notified about our new content and videos so stay tuned and all the best
Info
Channel: Code Maze
Views: 59,456
Rating: undefined out of 5
Keywords: dotnetcore, aspnetcore, errorhandling, exceptionhandling, logging, csharp, exception, trycatch, exception handling, error handling, error, try catch block, asp net core, dot net core, c#, exceptions, errors, .net core, asp.net core, asp.net core exception handling, .net core exception handling, c# exception handling
Id: tk1QK71DVtg
Channel Id: undefined
Length: 9min 1sec (541 seconds)
Published: Fri Feb 14 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.