The Right Way To Return API Errors in .NET

Estimated read time: 1:20

    AI is evolving every day. Don't fall behind.

    Join 50,000+ readers learning how to use AI in just 5 minutes daily.

    Completely free, unsubscribe at any time.

    Summary

    In this video, Nick Chapsas introduces the standardized way in .NET to return errors through HTTP API responses using the RFC 9457 specification, which replaced the older RFC 7807. He walks through implementing error handling for invalid units in a weather API example and demonstrates how to customize error responses with additional context like request ID and trace ID. Nick explains how to integrate global exception handling using custom classes like a Problem Exception Handler. Finally, he shares how developers can choose between different approaches to handle errors in their APIs.

      Highlights

      • Nick explains the new RFC 9457 for standardized error handling in .NET APIs. ๐Ÿ“œ
      • Demonstrates a weather API example to handle invalid input units. ๐ŸŒฆ๏ธ
      • Shows how to enhance response details using request ID and trace ID. ๐Ÿ”
      • Explores implementing global exception handling using custom classes. โ˜๏ธ
      • Discusses the merits of different error handling approaches in .NET. โš–๏ธ

      Key Takeaways

      • Learn about the new RFC 9457 standard for returning errors in .NET APIs. ๐ŸŒŸ
      • Implement error handling for invalid units in your APIs using Nickโ€™s example with a weather API. ๐ŸŒฆ๏ธ
      • Customize your error responses by adding context like request ID and trace ID. ๐Ÿ•ต๏ธโ€โ™‚๏ธ
      • Explore the use of a Global Exception Handler for more efficient error management. ๐Ÿค–
      • Compare different methodologies to choose the one that fits your style of error handling best. ๐Ÿ•น๏ธ
      • Discover discounts on .NET design pattern courses through Nick's channel. ๐Ÿ“š

      Overview

      In Nick Chapsasโ€™s video, we dive into a new standardized method for handling errors in HTTP APIs using .NET. The focus is on implementing RFC 9457, replacing the previous RFC 7807, to render development smoother and error handling more consistent across applications.

        Nick uses a practical weather API example to show how incorrect input units can be gracefully managed, ensuring API responses are purposeful and informative to the user. The demonstration covers updating response details by embedding request ID and trace ID for better debugging and tracing capabilities.

          Apart from basic implementations, Nick explores advanced handling by creating a global exception handler. This approach centralizes error management, making applications more robust. Nick wraps up with insights into different styles of error handling, allowing developers to choose a model tailored to their needs.

            The Right Way To Return API Errors in .NET Transcription

            • 00:00 - 00:30 hello everybody I'm Nick and in this video I'm going to show you what is the new standardized way of returning problems through HTTP API responses and I'm going to show you how to implement in net and this is what you would use if you return a validation error for example and things like that now this is implementing the RFC 9457 if I'm not wrong which is a standardized way in RFC agreed standard on how we should do this we can actually see it over here it came out a year ago in July 2023 and it finds how this
            • 00:30 - 01:00 should all look it obsoletes the preview 7807 and it's primarily on carrying machine readable details of errors in HTTP API responses and because apis are primarily read by machines this just standardize the way to do this so let me just show you what I have here I have an weather API but it's using a real weather API behind the scenes so if I go here what you'll see is I'm calling the open weather map API and I'm passing down the city and the units Fahrenheit
            • 01:00 - 01:30 Celsius and so on and then I'm getting the weather for a city so if I run this API and I go to insomnia and I say give me the weather for London in Celsius then I'm going to send this request and as you can see I'm getting the current weather now for London if I say give this to me for Fahrenheit I'm going to get Fahrenheit if I say give this to me for Kelvin I'm going to get Kelvin and I can change the cities to Paris to Warsaw to whatever I want so this is using the current real weather now the the problem
            • 01:30 - 02:00 arises when I have an input on the unit that is not a standardized one so if I have Celsius or Fahrenheit on Kelvin and to be honest this shouldn't really be here this should kind of be in the get weather for CTA sync method but I want to simplify how the demo is going so that's why I'm going to keep it here but you wouldn't do this here you would do it in here instead and the problem is how what do you return here right well probably you would return something like this you would say return results and then you say bad request and you would
            • 02:00 - 02:30 have an object specific to your bad request and you might say for example error is inv valid units and potentially message equals whatever you can only use Kelvin Celsius or Fahrenheit and then what would happen if you went and you called the API with inv valid units you would get a 400 battery request with inv valid units and you can do that and you can have your standardized way of doing it but now we have the standard proper way of doing this and we actually for a while now had the problem or validation
            • 02:30 - 03:00 problem which is more specific to validation on returning what happened so we're going to see how we can use that and not only that we're going to see how we can use an exception Handler as well to make this more Global so we don't have to have it here if we don't want to so the first thing we can do is we can just Define all the properties here so we can say type bad request then we can say title invalid units then we can say details units can only be C for Celsius or F for Fahrenheit or if we include a Kelvin as well we can say c um f or k
            • 03:00 - 03:30 you can customize that to whatever you want and then we can also say that status code should be status codes. 400 by request the moment we do that and we run the API I can go back and call this bad end point and I can call this API and I'm getting my response back right so this is the simplest way you can use this new RFC but this is a bare minimum and we actually want to go a bit further and we want to implement this more global scale and in different ways and
            • 03:30 - 04:00 we can extend it actually the first thing is that if you see we have very minimal details here and if you want to debug and know exactly what's going on we don't really have much information about the request itself so we can add that by going up here and saying build. service. add problem details and we can customize the options so a few things I would want to see for example is request ID and Trace ID and I'm also going to add instance those are all part of the standard response so what I want to say
            • 04:00 - 04:30 here is options do customize on problem details and then get the problem details context and in here I'm going to say context. problem details. instance equals and I'm going to use this concatenated string with the request method so get post or whatever and then the path to know which request cause that obviously you know it because you're copying it but if someone copies the response or dumps it somewhere maybe in a log message this just makes it easier to know exactly what happened then we can say the same thing context.
            • 04:30 - 05:00 problem details. extensions and we can try to add the request ID here as well so I'm going to say request ID and then I'm going to say context. HTTP context. Trace identifier so just the string identifying um the request the ID of the request the last thing I want to do is get the activity by doing context. HTP context features get get the ihp activity feature and then say context. problem details. extension
            • 05:00 - 05:30 and say try add the trace ID as well so what we want to say is activity do ID here we go and if this is null add nothing and by just doing that without actually changing anything in our code down here for all of our requests now that are returned as a problem if I call this I'm going to also get the instance the request ID and the trace ID extremely extremely useful and you can just say here's this Trace ID or here's this request ID go and correlate and tell me exactly what happened so now
            • 05:30 - 06:00 that I have that my API uses this new standard and everything is nice and clean but we might not want to do this here especially if we have a standardized way for returning these sorts of problems or validation exceptions or whatever it is I'm not necessarily a fan of this approach I'm going to show you now but I know tons of people use it and different architectures recommend it so I have to show it what I'm going to do is go here and create a new class and call it problem exception Handler so I'm going to stop this a API and in here I'm also
            • 06:00 - 06:30 going to create a model to represent this problem so what I will have is a problem exception extending the normal exception we can actually also say serializable here and then we have an error we have a message and we pass the message here and the error we store and then now we have the Handler and what I want to add in the Handler is the following I'm going to inject because I added this add problem details thing which now registers a service for me and that service is private read only I problem details service so I'm going to
            • 06:30 - 07:00 inject this one in here and I'm going to implement the I exception Handler interface which gives me this value task Boolean method called handle a sync with a context exception and a cancellation token so this will allow me to have Global error handling if I want to and to register all this all you need to do is go to the program.cs and say builder. services. add exception Handler and I'm going to use the problem exception
            • 07:00 - 07:30 Handler over here and I'm also going to have to register the middleware above everything else so app do use exception Handler so now it is registered but I need to implement it so what do I want to say here well I only want to care about this type of exception for now but if you have a validation exception or any other exception you can implement it here so what I'm going to say is if exception is not the problem exception I'm going to say problem exception then just return true and and well I can
            • 07:30 - 08:00 actually change this to aing because I'm going to have some awaiting going on here so if not return true otherwise I want to define a problem details object which is a new problem details here we go and this is an asp net call class and I'm going to have the same things as before so the status status codes and that is a 400 because that's how we represent validation problems then the title which I'm going to get from the problem details that I extracted from over here the problem exception so error goes here then I have the details which
            • 08:00 - 08:30 is problem exception. message and then I'm going to say type is bad request here we go so now I have a problem details and how do I write them well all I say is return await problem details service try write a sync new problem details context and we're going to write the HTTP context over here so HTP context and then we also going to write the problem details so you can have additional metadata as well but but I'm just going to write that so just by
            • 08:30 - 09:00 adding that now if I go back to my program.cs and I remove this I'm just going to comment this one out because you want to grab the code from the description down below to just play around with it I'm going to say Throw new problem exception and I'm going to put down the error which is invalid units here we go and then I'm going to add the message and if I just go now and I run this API Watch What Happens my API is running if I have a valid set of units this all works fine Celsius
            • 09:00 - 09:30 Fahrenheit but if I say a which doesn't exist then I have the exact same experience bad request invalid units status 400 but this is units can only be c f or K now we have a bit of a problem this is a 500 now not a 400 so I'm going to have to write the appropriate status code as well do this all you have to say is HTTP context over here and then response and then status code equals 400 or I'm just going to grab it from here
            • 09:30 - 10:00 and then paste it if I just hot reload and I go and I run my endpoint again now I'm getting f00 so you have full access to the response here you can do whatever you want otherwise everything just goes and flows naturally now whichever approach you want to follow it's completely up to you I'm more of a camp of the on the first approach and I would actually use functional programming and monads as well for this But whichever one you choose completely up to you both of them work and the global exception Handler is a great feature in general and the problem details you can inject
            • 10:00 - 10:30 them to anywhere to just write those responses if you need them and anything you add in that problem details thing over here will work now before I wrap it up I'd like to let you know that we just released 23 brand new courses on design pattern in.net we're covering basically every design pattern the first to 100 of you can use discount code patterns 20 at checkout to get an additional 20% to the existing 20% because bundles are always discounted on dome train so check the link in the description down below and now I know from you did you know about
            • 10:30 - 11:00 this and what approach would you follow to do something like this leave a comment down below let me know well that's all I had for you for this video thank you very much for watching and as always keep coding