Clean Architecture Demo
Toggle main menu visibility
Loading...
Searching...
No Matches
ExceptionHandlingMiddleware.cs
Go to the documentation of this file.
1
// TaskManagement.API/Middleware/ExceptionHandlingMiddleware.cs
2
using
Microsoft.AspNetCore.Mvc;
3
4
namespace
TaskManagement.API.Middleware
;
5
22
public
sealed
class
ExceptionHandlingMiddleware
23
{
24
private
static
readonly Action<ILogger, string, Exception?> LogRequestFailure =
25
LoggerMessage.Define<
string
>(
26
LogLevel.Error,
27
new
EventId(1000, nameof(
ExceptionHandlingMiddleware
)),
28
"Request failed: {Message}"
);
29
30
private
readonly RequestDelegate _next;
31
32
private
readonly ILogger<ExceptionHandlingMiddleware> _logger;
33
34
public
ExceptionHandlingMiddleware
(
35
RequestDelegate next,
36
ILogger<ExceptionHandlingMiddleware> logger)
37
{
38
_next = next;
39
_logger = logger;
40
}
41
42
public
async Task
InvokeAsync
(HttpContext context)
43
{
44
ArgumentNullException.ThrowIfNull(context);
45
46
try
47
{
48
await _next(context).ConfigureAwait(
false
);
49
}
50
#pragma warning disable CA1031
51
catch
(Exception ex)
52
#pragma warning restore CA1031
53
{
54
LogRequestFailure(_logger, ex.Message, ex);
55
await WriteErrorResponseAsync(context).ConfigureAwait(
false
);
56
}
57
}
58
59
private
static
Task WriteErrorResponseAsync(HttpContext context)
60
{
61
context.Response.ContentType =
"application/json"
;
62
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
63
return
context.Response.WriteAsJsonAsync(
new
ProblemDetails {
64
Title =
"An unexpected error occurred"
,
65
Status = StatusCodes.Status500InternalServerError,
66
Detail =
"Please try again later or contact support."
67
});
68
}
69
}
TaskManagement.API.Middleware.ExceptionHandlingMiddleware.InvokeAsync
async Task InvokeAsync(HttpContext context)
Definition
ExceptionHandlingMiddleware.cs:42
TaskManagement.API.Middleware.ExceptionHandlingMiddleware.ExceptionHandlingMiddleware
ExceptionHandlingMiddleware(RequestDelegate next, ILogger< ExceptionHandlingMiddleware > logger)
Definition
ExceptionHandlingMiddleware.cs:34
TaskManagement.API.Middleware
Definition
ExceptionHandlingMiddleware.cs:4
src
TaskManagement.API
Middleware
ExceptionHandlingMiddleware.cs
Generated by
1.18.0