Skip to content

Commit 419d068

Browse files
authored
Add option to ExceptionHandlerMiddleware to choose status code based on exception (#33438)
1 parent 0a668af commit 419d068

File tree

3 files changed

+59
-1
lines changed

3 files changed

+59
-1
lines changed

aspnetcore/fundamentals/error-handling.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: Discover how to handle errors in ASP.NET Core apps.
55
monikerRange: '>= aspnetcore-3.1'
66
ms.author: tdykstra
77
ms.custom: mvc
8-
ms.date: 05/30/2024
8+
ms.date: 08/25/2024
99
uid: fundamentals/error-handling
1010
---
1111
# Handle errors in ASP.NET Core
@@ -70,6 +70,10 @@ The following code uses a lambda for exception handling:
7070

7171
:::code language="csharp" source="~/fundamentals/error-handling/samples/7.x/ErrorHandlingSample/Snippets/Program.cs" id="snippet_UseExceptionHandlerInline" highlight="5-29":::
7272

73+
Another way to use a lambda is to set the status code based on the exception type, as in the following example:
74+
75+
:::code language="csharp" source="~/fundamentals/error-handling/samples/9.x/ErrorHandlingSample/Program.cs" id="snippet_lambda" highlight="2,6-11":::
76+
7377
> [!WARNING]
7478
> Do **not** serve sensitive error information to clients. Serving errors is a security risk.
7579
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>net9.0</TargetFramework>
5+
<Nullable>enable</Nullable>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
9+
</Project>
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
using Microsoft.AspNetCore.Builder;
2+
using Microsoft.AspNetCore.Hosting;
3+
using Microsoft.AspNetCore.Http;
4+
using Microsoft.Extensions.Hosting;
5+
using System;
6+
using Microsoft.AspNetCore.Diagnostics;
7+
using static System.Net.Mime.MediaTypeNames;
8+
9+
namespace ErrorHandlingSample
10+
{
11+
public class Program
12+
{
13+
public static void Main(string[] args)
14+
{
15+
16+
//<snippet_lambda>
17+
var builder = WebApplication.CreateBuilder(args);
18+
builder.Services.AddProblemDetails();
19+
var app = builder.Build();
20+
if (app.Environment.IsDevelopment())
21+
{
22+
app.UseExceptionHandler(new ExceptionHandlerOptions
23+
{
24+
StatusCodeSelector = ex => ex is TimeoutException
25+
? StatusCodes.Status503ServiceUnavailable
26+
: StatusCodes.Status500InternalServerError
27+
});
28+
}
29+
//</snippet_lambda>
30+
app.MapGet("/", () => "Hello World!");
31+
32+
app.MapGet("/timeout", () =>
33+
{
34+
throw new TimeoutException();
35+
});
36+
37+
app.MapGet("/exception", () =>
38+
{
39+
throw new Exception();
40+
});
41+
42+
app.Run();
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)