One of the many benefits of working with JSON:API and GraphQL is having a standardize way to communicate failures to a client. If you are not working with a spec like JSON:API or GraphQL, then you are in the hands of the developer that built the API and every developers implements error handling differently.
Almost every HTTP API that I've consumed implements errors differently. Can we just agree to use Problem Details and be done with it?— Derek Comartin (@codeopinion) April 11, 2021
RFC 7807, better known as “Problem Details for HTTP APIs” was created to standardize the way errors are handled in web APIs. Even though the RFC was published in 2016, it is not well-known, in fact, I myself did not know about it until 2019. To help spread the knowledge and usefulness of using “Problem Details” I would like to demonstrate how you can utilize it in .NET.
.NET already comes with a problem details class. No need to import extra packages. The problem details class has the following properties.
- Detail: A human-readable explanation specific to this occurrence of the problem.
- Extensions: Gets the IDictionary<TKey,TValue> for extension members. Problem type definitions MAY extend the problem details object with additional members. Extension members appear in the same namespace as other members of a problem type.
- Instance: A URI reference that identifies the specific occurrence of the problem.It may or may not yield further information if dereferenced.
- Status: The HTTP status code(RFC7231, Section 6) generated by the origin server for this occurrence of the problem.
- Title: A short, human-readable summary of the problem type.It SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization(e.g., using proactive content negotiation; seeRFC7231, Section 3.4).
- Type: A URI reference RFC3986 that identifies the problem type. This specification encourages that, when dereferenced, it provide human-readable documentation for the problem type (e.g., using HTML W3C.REC-html5-20141028). When this member is not present, its value is assumed to be “about:blank”.
To demonstrate how to use RFC 7807 on .NET I will create a new dotnet web api project by running the following dotnet command.
Within this new web api I will create a new exception handling middleware. The purpose of this middleware is to act as a mapper between an exception and a problem details json document. Basically, when an exception is caught by the middleware, it will extract metadata from the excepton to produce a Problem Details object.
Microsoft has some really good documentation on how to handle errors in .NET Web APIs, see Handle errors in ASP.NET Core web APIs.
Here is the middleware class definition without any mapping logic.
When you create a new .NET web api it comes with a weather forecast controller, the controller returns an in-memoery list of weather forecast. I will use this controller to test my middleware, instead of returning a list of weather forecast, the GET() method will be changed to throw a new not implemented exception.
To handle the GET() method throwing an exception I will need to modify the HandleException method within the middleware. The code below is the my first attempt at handling the exception.
As you can see the method extract information from the exception object. The exception name is used as the title, the exception message is used as the detail and the current request uri is used as the instance. Since this is just sample project, the type field will simply point to the MDN docs that corresponds to the HTTP status returned by the middleware. In your project, the type property should point to some documentation that provides addtional details.
The extension methods WriteAsJsonAsync and GetDisplayUrl are part of Microsoft.AspNetCore.Http.Extensions. The method WriteAsJsonAsync is only available in .NET 5 and above.
When an HTTP GET request is sent to /weatherforecast the not implemented exception is handled by the middleware, producing the following HTTP response.
Great, I’m pretty happy with my first implementation, later on I’ll extend my implementation by introducing my own problem details type. For now I do want to make the title more human readable, to accomplish that I will rely upon Humanizer. Humanizer will tansform “NotImplemnetedException” into “Not Implemented Exception”. To install humanizer, run the following command.
With humanizer now installed, I’ll modify the HandleException method again.
Running the same HTTP request yields the following result.
I now want to extend the problem details class. I want to include additional types, and move the logic that extracts data from the exception into another class. This specialize problem details class can accept an expcetion as a parameter, the class would then create a problem details document out of the exception context. The idea is very similar to how the ValidationProblemDetails class works.
The class will be named ExceptionProblemDetails, for now it will have three constructors, the default constructor, one constructor that take an exception and a constructor that takes an exception and an httpcontext.
The first constructor doesn’t do anything, it assumes that the developer will fill all the property, this is an a good option for developer that prefer to their own style of metadata extraction. The second constructor just provides some good defaults i.e. 500 as the status code. The last constructor is where most of the exception metadata will be extracted. It simplifies the HandleException method.
Here is response produces by the middleware now.
Perfect, though you should note that in your implementation, you should return a more detail error message, not just “Server encountered an error, please try again.”. I did that here in order to keep the example simple, it is up to your on how to implement the friendly error message, be that having a switch statment that handle each exception, perhaps having the content live in another API and then fetching it when the exception occurs, or you may try implementing your own exception class that provides all the required metadata.