File tree Expand file tree Collapse file tree 2 files changed +34
-16
lines changed
Expand file tree Collapse file tree 2 files changed +34
-16
lines changed Original file line number Diff line number Diff line change 1+ using Microsoft . AspNetCore . Builder ;
2+ using Microsoft . AspNetCore . Diagnostics ;
3+ using Microsoft . Extensions . Logging ;
4+ using Microsoft . AspNetCore . Hosting ;
5+ using Microsoft . AspNetCore . Http ;
6+ using Microsoft . Extensions . Hosting ;
7+
8+ namespace SampleWebApiAspNetCore . Helpers
9+ {
10+ public static class ExceptionExtension
11+ {
12+ public static void AddProductionExceptionHandling ( this IApplicationBuilder app , ILoggerFactory loggerFactory )
13+ {
14+ app . UseExceptionHandler ( errorApp =>
15+ {
16+ errorApp . Run ( async context =>
17+ {
18+ context . Response . StatusCode = 500 ;
19+ context . Response . ContentType = "text/plain" ;
20+ var errorFeature = context . Features . Get < IExceptionHandlerFeature > ( ) ;
21+ if ( errorFeature != null )
22+ {
23+ var logger = loggerFactory . CreateLogger ( "Global exception logger" ) ;
24+ logger . LogError ( 500 , errorFeature . Error , errorFeature . Error . Message ) ;
25+ }
26+
27+ await context . Response . WriteAsync ( "There was an error" ) ;
28+ } ) ;
29+ } ) ;
30+ }
31+ }
32+ }
Original file line number Diff line number Diff line change 1515using Microsoft . Extensions . Logging ;
1616using Microsoft . Extensions . Options ;
1717using Newtonsoft . Json . Serialization ;
18+ using SampleWebApiAspNetCore . Helpers ;
1819using SampleWebApiAspNetCore . MappingProfiles ;
1920using SampleWebApiAspNetCore . Repositories ;
2021using SampleWebApiAspNetCore . Services ;
@@ -102,22 +103,7 @@ public void Configure(
102103 else
103104 {
104105 app . UseHsts ( ) ;
105- app . UseExceptionHandler ( errorApp =>
106- {
107- errorApp . Run ( async context =>
108- {
109- context . Response . StatusCode = 500 ;
110- context . Response . ContentType = "text/plain" ;
111- var errorFeature = context . Features . Get < IExceptionHandlerFeature > ( ) ;
112- if ( errorFeature != null )
113- {
114- var logger = loggerFactory . CreateLogger ( "Global exception logger" ) ;
115- logger . LogError ( 500 , errorFeature . Error , errorFeature . Error . Message ) ;
116- }
117-
118- await context . Response . WriteAsync ( "There was an error" ) ;
119- } ) ;
120- } ) ;
106+ app . AddProductionExceptionHandling ( loggerFactory ) ;
121107 }
122108
123109 app . UseHttpsRedirection ( ) ;
You can’t perform that action at this time.
0 commit comments