Standardize Your Web API's Error Response With ProblemDetails Class

Often, RESTful services need to include error details in the error response along with HTTP Statuscode ( Be it Internal Server Error - 500, Bad Request - 400, ... ).

And if you are doing it by wrapping the error details in some random JSON properties, wait, I know a better way.

Return an Object of ProblemDetails Class

When working with Web API, you can return an instance of this class by calling Problem() method by providing appropriate arguments. You can find more about ProblemDetails Class at this official documentation link. An example will always make things easy to understand.. right? Let's see an example scenario.


Return a Status Code 507 ( insufficient storage ) along with appropriate error details when a client requests huge data from a RESTful API



In case you want to add more details to the error response, use the Extensions property of ProblemDetails class. 

Please note that when you want to use the Extensions property to add additional details to the error message, you CANNOT use Problem() method as it does NOT take any argument that corresponds to the Extensions property. One way to achieve this is to create the ProblemDetails Object directly and return it. See below.




So, this way devs can standardize the error response format in a RFC-Compliant way which can be understood both by machines and humans.

Your comments are always welcome :)