-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathExceptionMiddleware.cs
57 lines (51 loc) · 1.42 KB
/
ExceptionMiddleware.cs
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using GlobalErrorHandling.Models;
using LoggerService;
using Microsoft.AspNetCore.Http;
using System;
using System.Net;
using System.Threading.Tasks;
namespace GlobalErrorHandling.CustomExceptionMiddleware
{
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILoggerManager _logger;
public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger)
{
_logger = logger;
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (AccessViolationException avEx)
{
_logger.LogError($"A new violation exception has been thrown: {avEx}");
await HandleExceptionAsync(httpContext, avEx);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong: {ex}");
await HandleExceptionAsync(httpContext, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var message = exception switch
{
AccessViolationException => "Access violation error from the custom middleware",
_ => "Internal Server Error from the custom middleware."
};
await context.Response.WriteAsync(new ErrorDetails()
{
StatusCode = context.Response.StatusCode,
Message = message
}.ToString());
}
}
}