-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExceptionMiddleware.cs
81 lines (71 loc) · 2.8 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Threading.Tasks;
using ExceptionMiddleware.Errors;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace ExceptionMiddleware
{
public class ExceptionMiddleware
{
#region Constructors
public ExceptionMiddleware(JsonSerializerSettings jsonSerializerSettings, RequestDelegate next,
IHostingEnvironment environment,
ILogger<ExceptionMiddleware> logger)
{
_jsonSerializerSettings = jsonSerializerSettings;
_next = next;
_environment = environment;
_logger = logger;
}
#endregion
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (InvalidRestOperationException invalidRestOperationException)
{
_logger.Log(LogLevel.Information, invalidRestOperationException,
"Exception Middleware caught an error");
context.Response.StatusCode = invalidRestOperationException.ResponseCode;
await
context.Response
.WriteAsync(JsonConvert.SerializeObject(new ExceptionDTO(invalidRestOperationException),
_jsonSerializerSettings));
}
catch (Exception exception)
{
_logger.Log(LogLevel.Error, exception,
"Exception Middleware caught an unhandled exception");
context.Response.StatusCode = 500;
if (!_environment.IsProduction())
{
var ex = exception;
do
{
await context.Response.WriteAsync(ex.Message);
await context.Response
.WriteAsync("\n##########################################################################");
await context.Response.WriteAsync(ex.StackTrace);
await context.Response
.WriteAsync("\n--------------------------------------------------------------------------");
ex = ex.InnerException;
} while (ex != null);
}
else
{
await context.Response.WriteAsync("Ups... Something bad happened :(");
}
}
}
#region Vars
private readonly JsonSerializerSettings _jsonSerializerSettings;
private readonly RequestDelegate _next;
private readonly IHostingEnvironment _environment;
private readonly ILogger<ExceptionMiddleware> _logger;
#endregion
}
}