Skip to content

Commit 3974dd5

Browse files
simplyfied exception handler
1 parent 4941983 commit 3974dd5

File tree

2 files changed

+34
-16
lines changed

2 files changed

+34
-16
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}

SampleWebApiAspNetCore/Startup.cs

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
using Microsoft.Extensions.Logging;
1616
using Microsoft.Extensions.Options;
1717
using Newtonsoft.Json.Serialization;
18+
using SampleWebApiAspNetCore.Helpers;
1819
using SampleWebApiAspNetCore.MappingProfiles;
1920
using SampleWebApiAspNetCore.Repositories;
2021
using 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();

0 commit comments

Comments
 (0)