-
Notifications
You must be signed in to change notification settings - Fork 25.1k
Description
Description
My goal is to have an API return problem details when the request is bad. The article describes various ways to achieve that and I used the suggestions in my code. My test case was posting an invalid body to an endpoint, e.g. invalid JSON, and when testing in the Development environment my code did as expected.
However, when doing the same test when not in the Development environment the API would never return problem details or invoke my configured exception handler, and instead the API consistently returned 400 Bad Request with an empty body no matter how I tried to configure the API.
After a lot of digging I finally found the explanation why the Development environment was different compared to other environments when the body of the request can't be parsed and an internet search revealed that I was not the only one. It's RouteHandlerOptions.ThrowOnBadRequest that by default is true only in the Development environment.
While it might be a good default it's confusing to read an article about how to customize error handling only to discover that for this specific case (an invalid request body) the customization doesn't work except in the Development environment. I believe this article can be improved by mentioning how RouteHandlerOptions.ThrowOnBadRequest affects the error handling behavior.
To ensure that a custom exception handler is always called on a bad request the following line of code can be used when configuring the application:
builder.Services.Configure<RouteHandlerOptions>(options => options.ThrowOnBadRequest = true);Page URL
Content source URL
Document ID
eb873689-7ef2-b9d0-f21b-adeca32daa24