Handling errors in ASP.NET Core Web API
When creating a RESTful HTTP API, status codes can be a good way to indicate to the client if a request was successful or not. But if there was a problem, how do you tell the client specifically what was wrong?
Here’s the most common thing I usually see. Here are two made up requests responses that I made, but these are based on real API’s that I’ve used recently.
The second example is a little different. We have a status code 200 OK; But in the actually body we have a success property which is defined as false. We are not using the status code in a meaningful way here.
So what do these two error responses have in common?
Well…they are errors, but beyond that, nothing, they have nothing in common, wouldn’t it be awesome if you had a standard way of defining errors from your HTTP API. Well I have some good news, it’s called the ProblemDetails API.
Here is an example of a JSON carrying JSON problem details:
Here’s a brief explanation explanation every member:
It’s perfectly fine to add additional members to your ProblemDetails API. Here is an example with “balance” and “accounts” added.
Clients consuming problem details MUST ignore any such extensions
that they don't recognize; this allows problem types to evolve and
include additional information in the future.
Curious on how this is implemented in .NET Core?
Here’s a great tutorial by code-maze on how to implement the ProblemDetails API in .NET Core.
Using the ProblemDetails Class in ASP.NET Core Web API
In this article, we are going to talk about the ProblemDetails class and how it plays a role in standardizing error and…