|
10 | 10 |
|
11 | 11 | namespace ReferenceProject.Middleware |
12 | 12 | { |
13 | | - /// <summary> |
14 | | - /// Middleware to handle exceptions. |
15 | | - /// It separates exceptions based on their type and returns different status codes and answers based on it, instead of 500 Internal Server Error code in all cases. |
16 | | - /// In addition, it writes them in the log. |
17 | | - /// </summary> |
18 | | - /// <remarks> |
19 | | - /// There is another way to do this - an exception filter. |
20 | | - /// However, a middleware is a preferred way to achieve this according to the official documentation. |
21 | | - /// To learn more see https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#exception-filters |
22 | | - /// |
23 | | - /// See also: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#unhandled-exceptions-handling |
24 | | - /// </remarks> |
25 | | - public class ExceptionMiddleware |
26 | | - { |
27 | | - RequestDelegate Next { get; } |
28 | | - ILogger Logger { get; } |
29 | | - IHostEnvironment Environment { get; } |
| 13 | + /// <summary> |
| 14 | + /// Middleware to handle exceptions. |
| 15 | + /// It separates exceptions based on their type and returns different status codes and answers based on it, instead of 500 Internal Server Error code in all cases. |
| 16 | + /// In addition, it writes them in the log. |
| 17 | + /// </summary> |
| 18 | + /// <remarks> |
| 19 | + /// There is another way to do this - an exception filter. |
| 20 | + /// However, a middleware is a preferred way to achieve this according to the official documentation. |
| 21 | + /// To learn more see https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#exception-filters |
| 22 | + /// |
| 23 | + /// See also: https://github.com/drwatson1/AspNet-Core-REST-Service/wiki#unhandled-exceptions-handling |
| 24 | + /// </remarks> |
| 25 | + public class ExceptionMiddleware |
| 26 | + { |
| 27 | + RequestDelegate Next { get; } |
| 28 | + ILogger Logger { get; } |
| 29 | + IHostEnvironment Environment { get; } |
30 | 30 |
|
31 | | - public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostEnvironment environment) |
32 | | - { |
33 | | - Environment = environment ?? throw new ArgumentNullException(nameof(environment)); |
34 | | - Logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
35 | | - Next = next ?? throw new ArgumentNullException(nameof(next)); |
36 | | - } |
| 31 | + public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger, IHostEnvironment environment) |
| 32 | + { |
| 33 | + Environment = environment ?? throw new ArgumentNullException(nameof(environment)); |
| 34 | + Logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 35 | + Next = next ?? throw new ArgumentNullException(nameof(next)); |
| 36 | + } |
37 | 37 |
|
38 | | - public async Task InvokeAsync(HttpContext context) |
39 | | - { |
40 | | - var body = context.Response.Body; |
41 | | - try |
42 | | - { |
43 | | - await Next(context); |
44 | | - } |
45 | | - catch (Exception ex) |
46 | | - { |
47 | | - // If context.Response.HasStarted == true, then we can't write to the response stream anymore. So we have to restore the body. |
48 | | - // If we don't do that we get an exception. |
49 | | - context.Response.Body = body; |
50 | | - await HandleExceptionAsync(context, ex); |
51 | | - } |
52 | | - } |
| 38 | + public async Task InvokeAsync(HttpContext context) |
| 39 | + { |
| 40 | + var body = context.Response.Body; |
| 41 | + try |
| 42 | + { |
| 43 | + await Next(context); |
| 44 | + } |
| 45 | + catch (Exception ex) |
| 46 | + { |
| 47 | + // If context.Response.HasStarted == true, then we can't write to the response stream anymore. So we have to restore the body. |
| 48 | + // If we don't do that we get an exception. |
| 49 | + context.Response.Body = body; |
| 50 | + await HandleExceptionAsync(context, ex); |
| 51 | + } |
| 52 | + } |
53 | 53 |
|
54 | | - async Task HandleExceptionAsync(HttpContext context, Exception ex) |
55 | | - { |
56 | | - int statusCode = 500; |
| 54 | + async Task HandleExceptionAsync(HttpContext context, Exception ex) |
| 55 | + { |
| 56 | + int statusCode = 500; |
57 | 57 |
|
58 | | - context.Response.ContentType = "application/json"; |
59 | | - context.Response.StatusCode = statusCode; |
| 58 | + context.Response.ContentType = "application/json"; |
| 59 | + context.Response.StatusCode = statusCode; |
60 | 60 |
|
61 | | - // We can decide what the status code should return |
62 | | - if (ex is KeyNotFoundException) |
63 | | - { |
64 | | - context.Response.StatusCode = StatusCodes.Status404NotFound; |
65 | | - } |
66 | | - else if (ex is DuplicateKeyException) |
67 | | - { |
68 | | - context.Response.StatusCode = StatusCodes.Status400BadRequest; |
69 | | - } |
| 61 | + // We can decide what the status code should return |
| 62 | + if (ex is KeyNotFoundException) |
| 63 | + { |
| 64 | + context.Response.StatusCode = StatusCodes.Status404NotFound; |
| 65 | + } |
| 66 | + else if (ex is DuplicateKeyException) |
| 67 | + { |
| 68 | + context.Response.StatusCode = StatusCodes.Status400BadRequest; |
| 69 | + } |
70 | 70 |
|
71 | | - await context.Response.WriteAsync( |
72 | | - JsonConvert.SerializeObject( |
73 | | - new ErrorResponse(ex, Environment.IsDevelopment()))); |
| 71 | + await context.Response.WriteAsync( |
| 72 | + JsonConvert.SerializeObject( |
| 73 | + new ErrorResponse(ex, Environment.IsDevelopment()))); |
74 | 74 |
|
75 | | - if (context.Response.StatusCode == StatusCodes.Status500InternalServerError) |
76 | | - { |
77 | | - Logger.LogError(ex, "Unhandled exception occurred"); |
78 | | - } |
79 | | - else |
80 | | - { |
81 | | - Logger.LogDebug(ex, "Unhandled exception occurred"); |
82 | | - } |
83 | | - } |
| 75 | + if (context.Response.StatusCode == StatusCodes.Status500InternalServerError) |
| 76 | + { |
| 77 | + Logger.LogError(ex, "Unhandled exception occurred"); |
| 78 | + } |
| 79 | + else |
| 80 | + { |
| 81 | + Logger.LogDebug(ex, "Unhandled exception occurred"); |
| 82 | + } |
| 83 | + } |
84 | 84 |
|
85 | | - class ErrorResponse |
86 | | - { |
87 | | - public ErrorResponse(Exception ex, bool includeFullExceptionInfo) |
88 | | - { |
89 | | - Error = new ExceptionDescription(ex); |
90 | | - if (includeFullExceptionInfo) |
91 | | - { |
92 | | - Error.Exception = ex; |
93 | | - } |
94 | | - } |
| 85 | + class ErrorResponse |
| 86 | + { |
| 87 | + public ErrorResponse(Exception ex, bool includeFullExceptionInfo) |
| 88 | + { |
| 89 | + Error = new ExceptionDescription(ex); |
| 90 | + if (includeFullExceptionInfo) |
| 91 | + { |
| 92 | + Error.Exception = ex; |
| 93 | + } |
| 94 | + } |
95 | 95 |
|
96 | | - public ExceptionDescription Error { get; set; } |
97 | | - } |
| 96 | + public ExceptionDescription Error { get; set; } |
| 97 | + } |
98 | 98 |
|
99 | | - class ExceptionDescription |
100 | | - { |
101 | | - public ExceptionDescription(Exception ex) |
102 | | - { |
103 | | - Message = ex.Message; |
104 | | - } |
| 99 | + class ExceptionDescription |
| 100 | + { |
| 101 | + public ExceptionDescription(Exception ex) |
| 102 | + { |
| 103 | + Message = ex.Message; |
| 104 | + } |
105 | 105 |
|
106 | | - public string Message { get; set; } |
107 | | - public Exception Exception { get; set; } |
108 | | - } |
109 | | - } |
| 106 | + public string Message { get; set; } |
| 107 | + public Exception Exception { get; set; } |
| 108 | + } |
| 109 | + } |
110 | 110 | } |
0 commit comments