Skip to content

How RouteHandlerOptions.ThrowOnBadRequest affects error handlingΒ #34245

@Liversage

Description

@Liversage

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

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis/handle-errors?view=aspnetcore-9.0#problem-details

Content source URL

https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/fundamentals/minimal-apis/handle-errors.md

Document ID

eb873689-7ef2-b9d0-f21b-adeca32daa24

Article author

@brunolins16

Related Issues

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions