Home > Back-end >  Hellang.Middleware.ProblemDetails error mapping
Hellang.Middleware.ProblemDetails error mapping

Time:09-29

I'm learning about using problem details middleware found here

I have the setup working all fine but I got curious why it's mapping validation errors differently than the default status code.

To explain better, in the sample repo provided by the owner try the following:
call https://localhost:54547/mvc/modelstate
response "status":422

In the project's Program.cs, comment out the MVC override AddProblemDetailsConventions (line 46) and call again
response "status":400

400 is the default status code for validation errors automatically inserted when you add the ApiController attribute to your controller.

In a previous discussion with the owner here, it was recommended to call AddProblemDetailsConventions

if you want to have 100% consistent error responses from your API (produced by the middleware).

I understand the middleware is to control the "format" of response error message to follow RFC7870, but why is it changing the error code for this example case? is 422 more specific/better practice than 400?

I tried to look for more details, but couldn't find any. like what other mappings are changed, or if there's a way to configure the middleware mapping for default validation error (since in our project we already have test suit asserting on 400 for validation scenarios).

CodePudding user response:

From that same conversation with the author you cited, he does mention a way to override the default status response code in this post.

Regarding the 422 status code; it's an opinion of mine that syntactically correct, but semantically invalid requests should return back a different status code than 400 Bad Request

He also mentions that not everyone may choose to follow that convention, so he provides a way to override the default:

Some people don't like it (often because it's part of the WebDAV RFC and not an "official" HTTP RFC (but this will soon change, with the inclusion of 422 in HTTPbis' upcoming HTTP Semantics RFC, which obsoletes RFC 7231), so I've added an option to change it:

And provides a link to the source code value of ProblemDetailsOptions.ValidationProblemStatusCode.

You can pass in the options value to the configuration like this to change the default back to a 400 status code:

services.AddProblemDetails(options =>
{
    options.ValidationProblemStatusCode = 400;
});

Or if you prefer to use the private configuration method like in the sample library:

private void ConfigureProblemDetails(ProblemDetailsOptions options)
    {
        options.ValidationProblemStatusCode = 400;

        // the rest of the code setup he used in the example
    }

As far as the other mappings that were changed, I don't see much in the source code that is configured by default apart from setting the status code to 500 if there is no status code present.

  • Related