-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionMiddlewareExtensions.cs
More file actions
43 lines (36 loc) · 1.53 KB
/
ExceptionMiddlewareExtensions.cs
File metadata and controls
43 lines (36 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using Entities.ErrorModels;
using Entities.Exceptions;
using Microsoft.AspNetCore.Diagnostics;
using Services.Contracts;
namespace XWebAPI.Extensions
{
public static class ExceptionMiddlewareExtensions
{
public static void ConfigureExceptionHandler(this WebApplication app, ILoggerService logger)
{
app.UseExceptionHandler(appError =>
{
appError.Run(async context =>
{
context.Response.ContentType = "application/json";
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature is not null)
{
context.Response.StatusCode = contextFeature.Error switch
{
NotFoundException => StatusCodes.Status404NotFound,
BadRequestException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError
};
logger.LogError($"Something went wrong: {contextFeature.Error.Message}");
await context.Response.WriteAsync(new ErrorDetails()
{
StatusCode = context.Response.StatusCode,
Message = contextFeature.Error.Message
}.ToString());
}
});
});
}
}
}