File tree Expand file tree Collapse file tree 3 files changed +59
-1
lines changed
error-handling/samples/9.x/ErrorHandlingSample Expand file tree Collapse file tree 3 files changed +59
-1
lines changed Original file line number Diff line number Diff line change @@ -5,7 +5,7 @@ description: Discover how to handle errors in ASP.NET Core apps.
55monikerRange : ' >= aspnetcore-3.1'
66ms.author : tdykstra
77ms.custom : mvc
8- ms.date : 05/30 /2024
8+ ms.date : 08/25 /2024
99uid : 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
Original file line number Diff line number Diff line change 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 >
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments