dotnet / dotnet/AspNetCore.Docs

How RouteHandlerOptions.ThrowOnBadRequest affects error handling

Open
#34,245 0 comments 7 reactions 1 assignee Claimed by @wadepickett View on GitHub
aspnet-core/svc fundamentals/subsvc Source - Docs.ms
Dominant language
C#
Stars
13.1k
Forks
24.6k
Avg merge
1d 3h
Merged PRs (30d)
97

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](https://stackoverflow.com/q/72952323/98607). It's [`RouteHandlerOptions.ThrowOnBadRequest`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.routing.routehandleroptions.throwonbadrequest?view=aspnetcore-9.0) 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:

```csharp
builder.Services.Configure(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](https://github.com/dotnet/AspNetCore.Docs/issues?q=is%3Aissue+is%3Aopen+eb873689-7ef2-b9d0-f21b-adeca32daa24)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.