BrandGhost

Coding ASP.NET Core Exception Middleware - Live Coding in C#

June 9, 2024
• 584 views
I have some YouTube tutorials to make on several topics - so I'm going to livestream the creation process and explain more things in depth!
View Transcript
coming through okay I'll get my speakers muted so we don't have a fun feedback loop I want to make sure I can get this going on LinkedIn properly last time I couldn't see the event which made it so that people sending messages and stuff I couldn't respond to which is kind of crappy for a live event if you're watching this recorded it might not matter so much to you but uh I'd like to see if I can kind of get this sorted out um so give me one moment here please the goal today is going to be walking through some actual code which is fun um and yeah I don't see it this is nuts okay well I'm sorry if you're on LinkedIn if you want to send messages um you can try tagging me in the comment because I can't see when I'm streaming this I can't see the event that got created and the way that the chat works from LinkedIn is that it goes through an event as a comment so I I truly am unable to see and I am trying my best to be able to respond to stuff so I apologize but um kind of like some of the previous videos that I've done uh not the Monday live stream that one's more about software engineering sort of in general career stuff in general this is going to be walking through code so we're going to be looking at some asp.net core middleware I'm going to get us set up uh doing that I'm going to be referring to some other code I have written on a another screen so I'll periodically be looking over to try and figure out what the heck I'm doing um because this this is the kind of thing that I'm not coding all of the time time but I find that I you know I'm starting off a new application a new web service I probably need something like this at some point so um we're going to be looking at middleware in particular just trying to get some stuff pulled up here so uh I'm going to get a new Visual Studio solution going on we will look at some exception handling middleware and this is kind of interesting because we can maybe we'll start off with sort of like the base case where you have some API built and if you're not familiar with asp.net core I'll kind of walk you through some of the very Basics when you have a request uh that's coming in and what happens when your API is being hit and we do have some stuff that's built in for like debugging it things like that you can basically get like a whole whole error screen um but I don't want to do that I want us to be able to uh potentially get to the point in this little live stream where we have some custom error handling messages and stuff like that going on so um let me go ahead and get my visual studio set up here and then I'll switch over to a different view so you can see my screen I also want to double check this is going to YouTube properly at the same time here so seems like it is I'll make sure that I myself get on the stream and then I can double check anything that's wonky as it's going on so okay I'm going to go ahead and make my asp.net core web API um we will call it error error middleware example I'm not sharing my screen yet give me one sec and we'll do that once it's in Visual Studio pulled up on my screen I'll get it shared here one sec it's probably an easier way to do that too okay um and now to share my face is going to disappear in just a second here so whoop um we'll do that and will bring my face back there I am cool okay so I've just gone ahead and made a sample application and this is going to be oh did I do the wrong no sorry I saw an HTTP file here and I was like hey what the heck is this um I don't use these yet so I'm going to skip over that but um this is the sample weather forecast so again I'm going to walk through a lot of this stuff from the very Basics right so the sample weather forecast application does come with some endpoints we can work with very simple stuff and oh man did it make controllers this is not what I wanted it to do I want it to use minimal apis I don't like using controllers now um okay let me see this is happening because I'm on my second computer that I do recording on and I do all of my development on another computer but I had to switch because of my microphone setup so um let's see I thought thought I picked that but I guess that's not what I want right I thought that was what I wanted but why did it you know what there's probably an option where it says minimal apis or not use controllers oh that's what I picked okay let me go I'll add this one in I'm just going to basically copy over um all this code get rid of some of this stuff sorry this is a bit of a mess to start with I'm just trying to do this quick so I can we don't need open API we'll get rid of that okay and I going to get rid of this other project sorry if that was a little bit confusing I just wanted to use minimal apis instead of controllers especially when I'm streaming here because I just want to have it all on one screen for you guys okay so using minimal apis we have an asp.net cor web service here so we will have uh the Builder pattern kind of getting us set up to go make the server for us um what else is going on here uh some Swagger stuff this is just for um API documentation we turn on https and then really what the entire server is doing here is that we just have this weather forecast rad so if you've worked in asp.net core before this is truly just the very beginner uh template application that you have to get up and running with so nothing fancy it's just a kind of a placeholder for us right so the way that this works in aspor is that we have routes that we can set up so this is going to be a get request that we can fulfill it's at slwe forecast and then we go basically do some fake work in this case to go return a forast and this with name allows us to have that in our doc comments uh or I guess I should saying the open uh API I got to watch out cuz I'm going to keep saying open AI instead of open API I apologize in advance for doing this I know it's going to happen but yeah this just gives it a name for us as well but we don't have to really worry about that so I'm going to go ahead and I'll back that up and we're going to end up getting rid of the weather forecast stuff or maybe maybe we'll stick with it I might as well stick with it but I want to show you guys when we get into error handling and stuff like that um and it's it's not going to be about error handling in the sense of recovering our application it's going to be about just having some more information when we have an error happen Okay few more things that I want to add for context here we do have stuff like Aspire we do have things like uh Azure uh application insights there's so many tools that we have available to us that will allow us to have information on our routes when things is going when things are going wrong things is going wrong my goodness okay it's not even early here I don't have an excuse for not being able to speak properly but um there's lots of tools that we have that can help us diagnose this stuff so my goal walking through this is not to say hey you got to go do this because this is the only way you're ever going to know how to handle errors on your apis literally not the case this is just to show you that you can do some stuff like this and I like going through examples like this because you might say hey I remember watching that live stream or watching that recording where Nick was talking about error middleware and you might go like it kind of draws a connection for you where you're like I don't need error middleware but I need something else that can have you know can handle requests and do some some Logic for me and that might help trigger in your head like hey maybe I need some other middleware so the goal is not to say hey look follow this pattern do it exactly this way this is the only way to build stuff this is just for ideas and I'm doing this because I'm going to be making YouTube videos about some of this content so I'm walking through it for me and you get the benefit of exploring it alongside me so remember you can ask questions and stuff in the chat I will try to answer as I'm going along if it happens to not be about the topic that we're going through that's cool too I'm happy to pause and answer I would much rather spend time on things that are important to you than just kind of blasting through this stuff cuz if I was just trying to blast through it I'd turn the camera off and I would code it up and be done with it so the weather forecast rad that we have if I go run this let's see I don't know what browser and stuff it's going to open in or what screen this other screen of course and it's zoomed in about a million percent which is funny so zoomed in literally all the way uh okay so we have this this is the Swagger page that we get pulled up here right so uh what was the route it's slwe forecast right so if we go hit that route we do get a weather forecast right this is just the return value off of that web API I can't see too sharp zoom in do you need me to zoom in on this more I can if you'd like um I'm I can't zoom in on everything else because when I'm streaming I'm using basically 4K resolution but I'm using one quarter of my monitor to show you guys what's up so if you need the code bigger let me know but if you're curious about like the text in the bottom and stuff like that like it's not going to happen on the stream you got to wait for the YouTube video so I apologize uh but you might just be trolling me with that so I appreciate it okay no good it's not a bad programming joke it's one of my favorites I just wanted to make sure because I am streaming it and I would feel very bad if I go through all this and people were like Nick we couldn't see a thing you were doing I have streamed before and I've mentioned this where I forgot that my or I thought my audio was on I didn't forget forgot to check it and I was like 15 minutes into helping people build a calculator and someone in the chat was like hey we can't hear you how embarrassing do you think that was okay so we have a weather forecast route at Works um nothing too exciting we didn't even code it it just came out of the box like that so what we can do from here though is we can talk about throwing exceptions right so instead of doing that at all we can go throw a new valid in oper invalid operation exception I'll start putting this onto a new line try to keep in mind that there's this chat in the top right so hopefully it fits and what happens if we go call this route it's launching a different screen so we go call this route it's really funny it looks like Chrome's not remembering my settings and or maybe it did I think I zoomed in on the the uh the Json so we hit weather forecast here right exception throne and then we get this page right so what's interesting here is that um we have this when we're debugging and we're looking at it in a browser but one of the things that is important for me and this is just like it's a personal development kind of thing so again as PE I can see people are joining the stream and stuff so I will kind of remind people as I'm going along what we're going to be looking at is putting in error handling middleware and what I would like to be able to do is have some type of Json structure and not a dedicated screen for this kind of stuff furthermore um the Json structure that we'd be looking at we have a couple things to be thinking about when it comes to apis and Reporting errors so it's not a it's not a simple thing to solve there are public apis that I've used where as a user which is a developer in this case right I call the API and it doesn't work and instead of just saying bad request and you're like well that sucks like what do I do like why is it a bad request right they actually give you some really valuable information like hey you didn't set this parameter or you did but it has to be type so having some type of verbose debuggable information as an API caller can be awesome personally I would like it to be almost codified I don't want to have to think about it for hitting a a visualized web page all the time um if I'm just debugging some stuff on my own this is totally fine of course like there's information here not a big deal but I would like to be able to put some middleware in place where we can go look at perhaps transforming what that looks like within the stack that we have so another thing to call out in case people oops I just spat on my computer don't do that another thing to call out if in case people aren't familiar with how this stuff works in asp.net is like we had an exception but our server didn't crash right so I put out a few YouTube videos recently talking about different exception handling patterns um this is a a perfect example of an exception being thrown right literally you can see it on my screen exceptions thrown and it doesn't bring down the whole application so for the most part I haven't gone and looked inside of the the code that does the handling of the routes like inside of the asp.net core code but I imagine there's a big old try catch around a lot of stuff and it allows us to continue it allows us to do this kind of thing regardless of what type of exception we throw right so if I change this to a timeout exception or let's do like new file not found exception right so where I'm going with this is that people don't like this type of pattern where you have uh basically a a TR catch like this the chat we need a big old try catch in life really yes yes we do so you know you could put some type of handling here but really people get up in arms about seeing this kind of stuff in COD because they go hey look you can't just catch every exception that's terrible don't do it but I bet you there's something like that behind the the hood here and like I said we could go dig up the code and go find this and prove it but like I'm going to go run this one now and let's go see if I pull it up by the way there is a a goal that I'm trying to accomplish here I'm just trying to walk you through some stuff to show you like where my head's at but weather forecast right oh did I not oh man I didn't put throw in front well that's embarrassing can we get hot reloading no my hot reload is not properly set up on here I should change the startup URL to but I'm not doing that okay so exceptions thrown right where's my browser there it is cool so my point is that I just threw a completely random different type of exception and we could go try a whole bunch more and I can guarantee you I would bet money on it that there isn't some try catch that has like a thousand different exceptions listed it's honestly probably something like an empty or sorry like a just catch all exception it probably is something very much like that and the reason why that's the case is because they need to be able to say look someone's calling this route and if we're just having a request to this route we should be able to say something went wrong tell the caller and not bring the entire server down that would be pretty catastrophic if we just had one route do something that was a little bit unexpected and the entire thing got killed off so there are absolutely times where putting a try catch every exception is acceptable I do it all of the time and that might make you feel a little bit uneasy but I definitely do it in situations where I have code that I'm calling that happens to throw exceptions and I don't have control over it or I can't possibly know every exception but I do know that if it fails regardless of an exception being thrown or a Boolean return value whatever it is sometimes there's exceptions used for control flow not my choice and I need to be able to sort of intercept that and say don't bring down the whole application I also don't know all the exceptions you can throw just keep going so now that we've seen that on routes we can have this type of thing what I want to be able to do is put some middleware in place where instead of having this screen pop up what I would like to do is create some Json structure that we can pass back so what I started to talk about before I was showing these examples is that when it comes to pass passing back error information to a caller there's a lot of things to think about here and one of the things is that if you have an API that you've built for a product let's say so let's say you're not even exposing this to other developers on purpose this is just for your back end uh and your front end communicating to your back end and you put some code in place that has too much debug information on the API calls that could be basically like security vulnerability because people can really start to see how your API is working they can start to try and execute different things on it so you're basically providing more information and someone might try to abuse it so there's lots of things to think about and it's really this balance between like what's going to help you and what's too much and if we have other scenarios we can think about like we're running the app with a debug build or we're in a debug environment versus a prod environment we can do different things like that um I'm just checking the chat public static task run sync runny sync this host cancellation token try finally is that what's inside there uh on the on the asp.net core code behind the scenes because I bet it's something like that right a try with a catch of any exception and a finally block yeah there we go in source of ASP core hosting there you go it's a thing that exists right so it's not the end of the world if you do it but the reason that people caution against it is because usually uh especially for more Junior developers it's like you have exceptions being thrown because you're you know you don't have a you don't understand better ways to communicate error state or um or state that is not expected and therefore it must be exceptional therefore you throw an exception and then you have code where you're like maybe it's not exceptional so we have to catch it and now there's try catches everywhere it's just people are trying to caution you against doing ridiculous things but there are cases where it's valuable so on the return types that I want to start looking at uh when we saw the weather forecast stuff coming back it was a nice Json structure what I think would be interesting to try doing is that we can package a standard format and what we're not going to do is build that standard result uh out we're just going to do it sort of on the on the error handling middleware so uh I don't I just don't think I'm going to have time to kind of show that we could do like a I don't know like a more generalized middleware that could package up every response but I do want to think about it through the perspective of the error middleware so that might sound a little confusing um but we're going to jump into the air middleware but I have to remember how to go add this because like I said at the beginning it's not every day I go do this so I think I have to go oh it's app use exception Handler cool so we got this thing here okay and we can actually put our own exception Handler into this how did I do this before ah I need this uh request delegate okay so I'm just looking at the code on my other screen so we basically end up having to wrap this sorry my keyboard's not sending Keys Strokes anymore I'm trying to put a close parentheses you can probably hear it on the microphone it's not being sent um that's funny co-pilot bug I suppose okay so when we go to use this we're going to have to go put a delegate into here for handling and the way that we need to do that is that there's a request delegate um um let's see how we can go structure this where's a good spot to put this one sec okay so yeah thank you very much add exception handling T and then inside though I need to go put this uh this run call and then I need to put in the middleware and in my example application I built it's uh it's a little bit more complicated like I have a uh class that's using dependency injection I don't know if we're going to get that far into it but um I'm going to start with just a method on this for now so I'm going to have a void um error Handler and then thank you co-pilot so we get something like this but this isn't quite right because I think this is the syntax and it's not that either can I use a task on this it's literally between two computers and I only have one Mouse so I'm trying to like do this at the same time okay um let's start with this I might have to jump over to the other computer super quickly but this I'm going to put a break point in here I think this is the request Handler request delegate no it's not apparently well let's check it it is a task okay so we will put a task here we'll make it a sank and whatever we're not going to do that per for now okay so we're going to write back that can I just write a sync there we go this should work um we can see that this is now not complaining at us and that way when we go to throw an exception inside of weather forecast now just by hitting this we should be able to hit our middleware so this is a start okay that's funny I I didn't even type I I don't know if you can see that but I didn't even type in weather forecast and hit enter and it already went here peculiar I don't know how that's possible but okay if you're watching this and you know how that was possible um because again you can see in the browser oh man I just clicked off but I had typed like that and it wanted to autocomplete but I hadn't hit enter yet and then it still did this so very interesting but okay now you can see that we hit this right this is basically like we put a big old TR catch around everything and now we're able to intercept and do something with the response so if I press F5 see like it didn't actually do it that's so weird I have to do it again because I don't know how it hit that code path before okay this is what I was expecting to see so it says oh no I don't think that the key is dodgy I think that there's like a prefetch thing or something weird like that but I don't know enough about what was going on especially through the the browser calls like this um this wouldn't happen if I was calling it obviously through a a direct uh API request but let's go try it I'm just curious I want to go run it again and see and I will try to take my time as I do this but so what I was doing was highlighting over and I'm going to start typing weather forecast but I'm going to tell you when I press enter so w just press W that's all that I pressed was W so I don't actually know what's happening there that's very odd um but I wonder if we go into the exception Handler what is the request right sorry this is where the text is going to be very small for a lot you so I apologize when I make YouTube videos I change my whole resolution so it's 1080p but um I'm not doing that here but it says on the request it says that I put in that whole URL I absolutely didn't I told you as I was typing I only pressed W so very odd very odd but are there headers perhaps or maybe I'm not even able to see them here oh there's the request it's like pre-flight or something prefetch I think that's what's doing it there's some weird prefetch thing going on so I don't understand it if you know more about this and you want to drop some knowledge bombs in the chat or if you're watching this record and you want to add some comments that would be awesome hello I love pizza I'm live streaming so I would love to eat any type of pizza that is top of for you my wife says hi it's her birthday and we're getting pizza um so that means I will have to go through this quick because there's going to be pizza so the prefetch is what's kicking in here but that's kind of besides the point but like I was saying if you know more about this and why that's happening uh kind of cool I wonder if there's cases where you need to handle that like or do particular things but that's kind of a a new thing for me okay so the error Handler is something we have control over but this is where I have to jump over to my other computer super quick because there is a way that we can go pull the exception information and it's based off of a feature that we have access to so one moment because I didn't plan very well for this because it's way over here I'm not even going to try to turn my camera to show you but if you haven't seen pictures of my desktop setup is like I don't know if I stretch my arms out to the sides I can't reach the ends of my monitors and then there's more beyond that so give me one sec happy birthday Mrs deed yes my wife's name is Leah and she's awesome okay okay so I can see the code on my other screen now so basically off of the context oops not const off of the context we have something that is called features and then we can get this other feature and I don't think it's called that co-pilot come on I think it's called exception Handler path feature yo how you doing I'm doing pretty good I was just telling people on the stream I'm getting pizza soon for my wife's birthday so I'm going to have to drop off in a moment but I hope I can get to the punch line of this cuz I think it's a pretty cool thing so um we'll get this feature pulled out I'm going to try spacing it down a little bit here and then okay on this thing we're able to get the error that came back I will let her know you say happy birthday thank you so much you will appreciate that she was doing some yard work and I wasn't um and then I figured I could sneak away and do some streaming uh so that I can get my YouTube videos ready and then she knocked on the door and said there's pizza coming so okay the next stage that we can do with this exception feature is we can ask for the error right so that's going to be the exception that gets thrown okay so I'm just going to pull this into another variable so we have it here um this is kind of interesting because I think this can potentially be null um if you forgot to turn off the feature somehow but I think it's going to be enabled by default for us so let's go ahead and we'll do something like this uh we're going to put that will this serialize Json for us if we pass an object in let's find out no that one will though okay so we can do something like um my goodness exception type so something like this just to start off okay so I'm going to go run this again how is the stream I think the stream's going well this is going to be about error handling middleware and asp.net core some of the framing for a YouTube video that I will be launching next week and I like trying to stream some of the content so you can guys can see it being put together so oops I got to do something with this pre-flight thing this is [Laughter] annoying okay so if we go into here we get this exception feature okay from there if I step over I know this is hard for you guys to see with the very small uh what's it called resolution so the the tool tips are really small so we do get the error that came out so that's cool um is there anything interesting to see on this I don't think there's anything it's it's coming back as a file not found exception so nothing thoughts on returning a problem details type class yeah so Nick Hodge that's sort of what we're going to be getting to is building like a custom problem details type of thing and then the goal is that I wanted to be able to show it getting wrapped up so you could essentially use like a standardized uh API like object so you could have like what's a good word for this it's like a um I'm drawing a blank here there's a word for it um something Union in discriminate Union I'm saying this wrong C doesn't have support for them it's that uh it's basically the ability to have like a multitype so I want to be able to do something like that but I was showing or I was explaining earlier we're not going to get to the Happy path so all the good calls aren't going to use that but at least we could show it kind of working discriminated Union thank you so much I I tell people that when it comes to making YouTube videos it's like um yeah one of exactly when it comes to making YouTube videos it's easy to like you can mess stuff up and you're like whatever I'm just going to edit it out but when you're live streaming it's like yeah like this is some insight into probably how much I mess up when I'm putting videos together but it's live I can't undo it and I think there's something nice about that you guys can see like what goes into this stuff being put together so I do want to be able to do something like that is build a essentially like a one of on the the return type so we can see there we go I'm just printing back Json instead of us getting that uh that screen right High latency pair programing with idiots like me well I wouldn't call you an idiot absolutely not but uh I think the pair programming point is very interesting because on one of the previous streams uh we were doing um downloading of files and the file downloading I was trying to look for headers and I had people in the chat being like hey check this check that it was truly like par programming and it I don't think they had the right answer but it at least pushed me in the direction to find the right answer so there is a ton of value in it uh stream I stream regularly on Monday nights 9:30 p.m. PST and that that is General software engineering advice so I'm a principal software engineering manager at Microsoft I've been programming for 21 years managing teams for 12 years and startups and Microsoft is Big Tech and the Monday night streams are General software engineering advice so you will not gen usually see me going into code on those streams but I put out YouTube videos I put about three YouTube videos out per week that are code I do a software engineering interview SL podcast is another video in the week so there's at least four videos that go out every week plus that Monday Night Live stream and then I try to show in my other streams that I can walk through code to go put those things together I as I see on your channel you have nothing on your channel I don't know what channel you're looking at if you're looking on Kick it's probably because I don't know how to use kick but my channel is here I'll put it in the chat so that is me hopefully that goes through in the chat doesn't look like it's getting sent to kick though that's super annoying it's basically Dev leader on YouTube um that's so funny the restream tool that I'm using the chat comes in from everywhere but it showed me that it went out to Twitch YouTube and Facebook so uh for the person messaging on Kick Queen Alexa see it I'm sorry that message did not go to you but you can see it in the in the Stream window I think right so hopefully you can check that out if you want to see my other videos um I haven't customized my kick yet so that's where you're looking it's not customized okay so this is the basics for error middleware right and we can do other things like we can put the trace on here so we can put the message thank you co-pilot I wanted to do the trace so we can do this kind of thing um something else that we might want to do is think about like a friendly message and a debug message uh I am planning to do customization at some point but I do so much content creation that I have not yet had a chance to go over and spend time on kick that's the short answer so these three things will provide back on here if we go have a quick look at this when it's running go back to the weather forecast um my goodness come on prefetch okay I'll Zoom back out so we can see now that we're getting some Json built up and again for me I liked having this because in the spots where I'm debugging this usually I have say two things written in C or I have even sometimes um say frontend code in typescript and I'm calling my API what I don't want to do is like I'm trying it in the browser I'm trying it in post man I'm like hey it's working cool and then I go try it in code I'm like it's not working and I have no useful information um sorry I'm not looking for services so thank you but no thanks um this part here if I were debugging and connecting some of my things that I was building together would be helpful for me so I know what's going on but there's more we can do right so something else that we could look at is doing something like fluent validation so let's go back into the code we could go do something like I don't know I'm not going to go build this properly so if you guys have seen fluent uh validation let's go over to I'm not going to go build a fluent validator because that pizza is going to be here not too long from now but we can do something like put in oh I'm in the wrong tab fluent validation right almost half a billion downloads it's very popular so pull that in and what you can do with fluent validations you can make these validators so you would inherit from this abstract validator and that way when your request comes in you can pass it into the the validator it can go validate for you and then you can basically write your validation Logic on your uh request in a way that's very easy for you to read as a programmer and then the result is that you can actually pass that information back so I'm not going to go build a whole fluent validator but if we assume that we were to call something right so we're going to go do the validation and if it fails so I'm just going to put if true right but imagine that was saying like if the validation was not successful we could go throw an exception here and this is where I would start to break some of my rules with flow control and I'm going to back up in just a second but I break some my rules for flow control in terms of exception throwing okay so the reason I'm saying this is generally what I like to do is never throw exceptions I don't like doing it however um I'm saying this and haven't yet put it into practice but as I'm writing out one of my current apis I'm getting to the point where I'm saying hey you know what I want to standardize my message responses and the error types that come back and one way that I can do that is instead of every single route trying to call some class that says Hey how do you go format this how do you go make this do the right thing what I could just do is let them throw exceptions when it's bad and the thing that I haven't fully figured out and the reason it's or sorry the reason I'm not going to be doing in this live stream is to standardize the return object and the happy path because I would like it to be wrapped up in something that is going to be uniform across every route that I have I think middleware could be a great option for that so I will explore that further but at least for errors what I don't want to do is like if the validation you know I don't want to have to go like call code to format um like specifically error response can't type there we go and then we'd have some other logic down here for some other error like you're trying to do authentication now or you're trying to do uh look up a resource that's not available and we have to keep calling something to format the error response I don't want to do that at all and especially because there's going to be code that we call out to and if that can throw an exception we still need something that's going to handle it in the middleware anyway so what I'm trying to do in my own code is switch over to be something like instead of formatting error responses here just throw an exception and let the middleware go tackle that for us so if the if the validation failed we could have a dedicated exception for that I'm just going to throw a format exception this is not what I would recommend so I'm just calling it out but we could do like new format exception validation failed missing um you forgot to put the ID on something okay so we could throw this exception and that shouldn't say return sorry throw and what else I cut out the forecast okay whatever it's not happy because I have an if true but I was just trying to show you like that's where validation would go um so yeah You' do some validation and if it failed right then you'd go into this code block and you would throw some exception that was like a validation exception that's the goal I'm just using format exception as an example here but that means if we go check out our air handler I'm going to show you what I would start to do and then I'll explain how I would start splitting this apart because what I'm about to show you makes me feel a little bit sick to my stomach but I have patterns for that that I like to move away from it's just that they introduce complexity and they don't make a lot of sense in the beginning and we're not going to get too far which is why jumping right into it is not going to help but what we could do is something like this so if error is format exception we go do something specific okay so if this was your validation so someone's sending you a request right and it's missing parameters and you're like hey I can't even I can't even fulfill the request you're trying to do and let me you know what just to make this a little bit more clear I'm going to make a validation exception thank you co-pilot makes this super easy I'm going to I'm going to do this specifically so that we feel like I'm not breaking too many rules here um but so we would catch this specifically in here and say hey it's a validation exception we know that in our stack this is only thrown when someone makes a request to us and we can't handle it based on the fact that they've left out data it's kind of like what you would normally get if you had a bad request response and that's what we're going to do so we can go ahead and basically you might do something like this so we would say uh context. response do status code uh 400 so we can do a 400 and then we can actually write back and this is where I would like to do a structure for this okay so if we had this is going to be a little bit hard to think through because I haven't fully figured it out yet ahead of time um but I would want to have a standard type of response I've already said this a couple of times so it might look something like I don't know some type of API response okay and we could have a um the data or we would have an exception so I would do something like this but exception I don't even feel good about um this is going to look super gross so I apologize so we'd have exception or error and then we could also do something like this is because we don't have uh as sorry I'm scrolling back in the chat as Nick hodj pointed out discriminated unions we don't have this ability in C but this is how I would probably want to structure some of this code and I would do a Bool when the error is null then we have a success so I would want to do something like this and I would write out a one of these and we could do that clean this up a little bit so you can see on my screen for here we're saying this is why it looks kind of gross because I still have to like make an API response I'm passing in null as the data but we are going to format an error object and again what we might want to do is provide different details here so this error object instead of just having a normal object we probably do want to give it a dedicated type I used object right now because I don't yet know what I want that type to be so if this were someone calling our API okay we have to think about who can call this and I hinted at this earlier if if it's our own service so one of the developers on our team is calling this we might want to be able to give them more information we might want to let them know like you're having the stack trays happen on the server and they can go oh I know what that that's going to mean I can debug this easier but the reality is like if someone if you had this publicly exposed you probably don't want to be sharing stack trases outside of your application so there's some things that we might want to do to get around that so for example this you could do this a million different ways right but you could do like if you're running this in debug you can stack this other information onto your error type you could do this kind of thing again I would not use just a normal object I would have a type for this so it would be strongly typed just a heads up but I'm not going through that quite yet so we' do this and then basically um we would start building out these other error types here so return after that and otherwise if we had a problem that was not a validation exception what we might do is something like um I I don't know let's see I'm got to copy this so pass a 400 back and we could still do an API response I'm missing one of these okay and then we could do like message like this so there's I'm not telling you uh how to do it I'm just showing you that you have some patterns that you can start to form here so what you start to see shaping up here is that if you have certain types of exceptions that could be common across your API uh calls such as validation exceptions right so anytime anyone's making a request to any API in your service you want to give them the validation details that come back out you could start to package them up in a nice way I'm not saying that what I built is nice I'm just saying that you could figure out whatever nice means to you um so you could go do that and I'm trying to call out that you have some other stuff that like is helpful when debugging but probably not in a production scenario so do be careful about that but let's go look through what we can start to have going on here so this is going to be a validation exception and this is going to complain at me but I'm going to put another exception here oh no this this is bad okay so we can't hit this yet is it going to run for us didn't complain this time okay it's unreachable code so I figured it would okay now it's going to do that silly thing it didn't that time it didn't do the prefetch okay so F5 again if I step through it is it a validation exception yes it is right so then we go into our special Logic for this we'll write a 400 back and then dedicate uh this very specific object as the return type and I am running in debug mode so we should get all of that data and then you can see uh and you can change your Json serialization so we can make it so that null on data never gets written out like this is kind of just extra information to pass back but you have to think about the API You're Building maybe you expect callers are looking for this all the time I like omitting nulls because in my opinion it's just extra data that's being sent and it's not offering value so if it's not there it's it's null um I treat those as the same thing but then you can see that we have an error coming back and trying to see it didn't put the success on there so we'd have to go change or like look at our Json serialization and see why success was not put on to that so I don't know if that means oh uh I didn't make it public it was a simple mistake so because it wasn't public the serializer didn't know to go pick it up let me go run it again okay so that time it did prefetch okay so if I press F5 again on this one I think we should see whether or not there's a success on and there is so you can see right here this could be very helpful on the calling side right you can basically decouple and this is just an opinion of mine you can decouple yourself from the HTTP status codes because there's some there's multiple status codes that can mean success it's not just 200 so someone might say if request equals 200 and then someone goes oh but I'm going to I think it's like a 206 or something like still a success but like basically if someone starts misusing the status codes or they have a slightly different meaning and you just want to know if the thing worked or there's no error you can use a flag for this there's so many different things you can do here again I'm not telling you what's right and what's wrong I'm just giving you options to think about when you're building this stuff yeah uh you can go ahead and ask about the courses on dome train I'm happy to answer I'll uh if you just want to type out whatever you're thinking I'll I'll kind of pause what I'm doing and answer you um so this is shaping up are there more like the are they more like the talks on the subject or they checkpoints with like projects oh good question um the structure of I'm trying to think for all three courses the factoring one is a little bit more like walking through some projects so they're mostly structured like um going through different pieces of information actually this is a good opportunity I know I'm go I didn't this isn't a plant by the way Jonathan C is not paid by me to ask about Dome draam courses but thank you for asking let me pause and I can explain because I don't I don't like to push courses I feel like if you're interested in that kind of stuff great um but it's not for me to um I think people learn best by doing right so I think people learn best by doing but I think that there are people who will go find courses are something that if especially if they pay for them they feel a sense of like I don't know uh they have to be committed to doing it there's an accountability part and the example that I like to give is that for for bodybuilding right I've been interested in bodybuilding for as long as I've been programming so I've been in the gym for like 21 years and I still paid for a coach not because I was like oh like they're going to teach me things I've never thought about or I don't know how to do my diet I know those things I've been doing it for 21 years but I was paying a coach because it made me feel accountable so for some people that can be helpful other people maybe not the case um but I'm going to go to choruses let's find this one for example so the I just wanted to find is there no link to just my name there so the refactoring one if we pull this one up um you can see that there's some things in here that are like projects but they are not getting you to go build projects so that's the thing that I want to call out I think the best way to go learn is to go off and build the projects but um the way that structure these for Nick chaps is is not um hey here's an outline for a project go build it and then come back I think that could be interesting um I would be happy to write choruses like that for Nick chaps is on dome train but the style of them is not quite like that so just to give you an example on this one right so like what is refactoring I walk through these Concepts I walk through these Concepts and show you how to go do these types of refactoring saying same thing here but in some of them I try to include like a demo where we go looking for more specific examples Hey John John is from latterly IO John is awesome it looks like my LinkedIn chat is actually working too so that's awesome um so on so Jonathan I think that they're for the most part you'll see people going through uh like bigger projects and stuff but I don't think that they basically tell you to go off and go build it and then come back I think that's the common pattern so um if you're looking for that kind of thing um I don't think you will find it exactly that way in these courses although in every course I put out one of the things I say in one of the first three videos of the course is make sure you're programming alongside me because I honestly feel that you will not learn your best unless you're doing that but yeah if you want if you have more questions about these courses you can uh definitely ask me uh on LinkedIn on X anywhere you want to reach out I'm going to put these in the chat in case folks are interested thank you for getting me to advertise my own stuff because I always forget to do it um so yes John who joined the chat um is from latterly IO I'm not sure if he's still on because I can't really see too too clearly from Ram but John's awesome so um we got a link to latterly IO can we drop that in here shout out to John um cool I'm going to go back to my code over here though so we were just looking at shaping up basically like a common response now again this API response object that we built if I go back here this is only getting used in the error case we would have to think about how we sort of enforce every API call to do it and instead what we could do is is have middle wear that will take any object you pass back and wrap it up for you um and John I'm going to be dropping off in just a moment anyway because I heard my wife I think she's going to pick up the pizza that was coming so it's her birthday and we're having pizza so the other thing I'm going to do is walk through this other scenario that we had so it's not a validation exception now right so we're not going to go hit our dedicated logic here and that's because we wrote this specifically for validation errors because we want to have more context like hey you forgot to add in uh this property on this Json object we were expecting especially if you're using fluent validation you could do some awesome stuff there let's see if we're going to get the prefetch stuff no okay so exceptions thrown right it's not a validation exception this one should be very lightweight in the response it's not going to tell us anything press F5 right you can see that we get this object uh style still where we have nothing for the data success is false but then we have this really lightweight message that's just like hey sorry this sucks but you can look into going to parse this type of thing now if you needed to or again if you're like me and you're just working inside of your client code calling your server I just want to be able to see what's up right so in fact if I go back into the code for my error Handler here basic whatever we see up here I would probably still have something like that here with some sort of a uh ifdef for debug or if I'm in development mode or something else I'd want to make sure that if I'm more air quotes here privileged to be able to see some type of error information that I can go check that out because using the error page is not going to be helpful to me if I'm calling this in code again this is all stemming from the fact that I am building client server uh web apis and I need to make sure that when I'm building out the calling code that when it's messing up I have clear indications as to why I'm not sitting there fumbling through stuff cuz you'll have ridiculous things where like just to give you an example um let's say we wanted to go return a new object back here okay so we're going to return a new this would get serialized into Json right so let's do I don't know what a good thing to do here is um value equals 1 two 3 okay so we go call this I just want to show you how simple some of these errors can be when you're kind of working with a web server and a client okay so we get value 1 2 3 but there's already something very interesting about this and I want you to have a close look put them side by side here if you pay close attention the word value and the word value were not the same one has a this seems ridiculous but one has a capital V and one has a lowercase V depending on your framework whatever you're using your Json serialization could literally say this with a lowercase V is not the same as the uppercase V I don't know what to do with that and I have absolutely myself written web apis where someone passes in the wrong um casing so your whole thing looks almost perfect and now you have to go find a word that has the wrong casing on it and hope that that's what's going to fix it so instead of having that type of of situation I like making sure that I can have some air middleware that really makes it obvious like hey like you know you don't have value set on here and you'd be like yes I do and then you're like why is it telling me values missing and then you have a closer look and you go oh right so having little things like that that point you at where the issue is can save you boat loads of time when you're debugging and that's why I wanted to put this example together and that's what this YouTube video that I will make of this is going to talk about so yeah John Caps comite good point good to see you you're probably already dropped off but John's an awesome guy if you don't know John I mentioned latterly IO in the chat um check him out he's on he's a lot more active on LinkedIn now but he's pretty big on the Tik toks so it's really cool to see John drop in he's uh he's got a lot of data about things that he talks about which I think is missing from a lot of creators including myself I use a lot of anecdotes this is all my experience but uh especially for people that are say more new in career they're doing their job search and stuff like that like laterally IO and what John talks about are it's all built around data he's got a PhD and economics and I love shouting that out because I think it's so rad but um he leverages like looking for data to back things up and is very data driven in his approaches so do check out laterally iio if you haven't heard of that and check out John on on Tik Tok and Linkedin okay that might be where I'm going to wrap this one up but I did want to shout out and mention where this is headed next because this will either be the next stream or if I don't get to it I will just create a YouTube video about it but I mentioned a couple times what we've been able to do is if we have errors that get thrown then we are going to have a common way thanks to middleware doesn't matter if we have this route or if we have a route right below it right some other route here doesn't matter anytime you throw a validation exception we will handle it in a consistent way this is super powerful when you're building apis it's super powerful for code maintenance so that you don't have if you keep scaling this out like a 100 different spots that have to know how to format something that should just be defined in one spot because if you change that behavior you don't want to go change it all those spots too so that's part of it and that's specifically for errors but now what happens if we want to have a common return type for errors and your happy path situation you don't want to have the same problem where everyone has to know how to go format things so I'm curious and trying to see if I can go right a middle where for the happy path that will package up any object and if we go look at this API response that I wrote on the data prop property we will package it up on the data property so every API response would have an object with a data property and it will also have a success flag on it right so if the error field is present success will be false if the data field is present success will be true and then you can have a more common parsing set of logic on the client side so that is what I will be building next happy birthday I will let my wife know you say happy birthday to her and and we also got cats yesterday so that was part of her birthday present we have two little kittens they're in the Next Room over um as these cats get a little bit older I am so pumped to bring them on stream they're so cute but they're too little right now they're scared of everything so okay folks I'm going to wrap it up here thank you so much I hope that you got to see something interesting with the air middleware here right we got to see this eye exception Handler path feature we got to see if I scroll back up use exception Handler and then you can hook up your own middleware super cool super powerful and other middleware lets you do other really interesting stuff as well so thanks folks I will be streaming Monday night 9:30 p.m. PST on software engineering topics do check it out um would love to see you there and if you have other things that you would like to see me stream about in code whether it's directly in C or you want to have more General software engineering topics please just reach out to me leave comments on stuff and just ask for what you want to see and I'm happy to try and put it together so thank you so much and I will

Frequently Asked Questions

What is the main focus of this live coding session?

In this live coding session, I'm focusing on implementing exception handling middleware in an ASP.NET Core application. I'll walk you through the basics of how middleware works and how we can create custom error handling messages for our API.

Why is exception handling middleware important in an API?

Exception handling middleware is important because it allows us to manage errors in a consistent way across our API. Instead of crashing the application or returning generic error messages, we can provide structured JSON responses that give more context about the error, which is helpful for debugging and improves the developer experience.

Can I ask questions during the live stream?

Absolutely! I encourage you to ask questions during the live stream. If it's not directly related to the topic, that's okay too. I prefer to address what matters to you rather than just rushing through the content.

These FAQs were generated by AI from the video transcript.
An error has occurred. This application may no longer respond until reloaded. Reload