-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHandlingMiddleware.cs
More file actions
137 lines (124 loc) · 4.92 KB
/
Copy pathExceptionHandlingMiddleware.cs
File metadata and controls
137 lines (124 loc) · 4.92 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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
using CCE.Application.Common;
using CCE.Application.Localization;
using CCE.Application.Messages;
using CCE.Domain.Common;
using FluentValidation;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CCE.Api.Common.Middleware;
public sealed class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context).ConfigureAwait(false);
}
catch (ValidationException ex)
{
await WriteValidationResultAsync(context, ex).ConfigureAwait(false);
}
catch (ConcurrencyException ex)
{
await WriteErrorAsync(context, StatusCodes.Status409Conflict,
"CONCURRENCY_CONFLICT", MessageType.Conflict, ex.Message).ConfigureAwait(false);
}
catch (DuplicateException ex)
{
await WriteErrorAsync(context, StatusCodes.Status409Conflict,
"DUPLICATE_VALUE", MessageType.Conflict, ex.Message).ConfigureAwait(false);
}
catch (DomainException ex)
{
await WriteErrorAsync(context, StatusCodes.Status400BadRequest,
"BAD_REQUEST", MessageType.BusinessRule, ex.Message).ConfigureAwait(false);
}
catch (System.Collections.Generic.KeyNotFoundException ex)
{
await WriteErrorAsync(context, StatusCodes.Status404NotFound,
"RESOURCE_NOT_FOUND_GENERIC", MessageType.NotFound, ex.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception");
await WriteErrorAsync(context, StatusCodes.Status500InternalServerError,
"INTERNAL_ERROR", MessageType.Internal, null).ConfigureAwait(false);
}
}
private static async Task WriteErrorAsync(
HttpContext ctx, int statusCode, string domainKey, MessageType type, string? fallbackMessage)
{
var l = ctx.RequestServices.GetService<ILocalizationService>();
var msg = l?.GetString(domainKey) ?? fallbackMessage ?? "خطأ";
var code = SystemCodeMap.ToSystemCode(domainKey);
var envelope = new
{
success = false,
code,
message = msg,
data = (object?)null,
errors = Array.Empty<object>(),
traceId = Activity.Current?.Id ?? ctx.TraceIdentifier,
timestamp = DateTimeOffset.UtcNow,
};
ctx.Response.StatusCode = statusCode;
ctx.Response.ContentType = "application/json";
await JsonSerializer.SerializeAsync(ctx.Response.Body, envelope, JsonOptions)
.ConfigureAwait(false);
}
private static async Task WriteValidationResultAsync(HttpContext ctx, ValidationException ex)
{
var l = ctx.RequestServices.GetService<ILocalizationService>();
var headerMsg = l?.GetString("VALIDATION_ERROR") ?? "عذرًا، البيانات المدخلة غير صحيحة";
var headerCode = SystemCodeMap.ToSystemCode("VALIDATION_ERROR");
var fieldErrors = ex.Errors.Select(e =>
{
var domainKey = e.ErrorCode;
var valCode = SystemCodeMap.ToSystemCode(domainKey);
var valMsg = l?.GetString(domainKey) ?? domainKey;
if (valMsg == domainKey) valMsg = e.ErrorMessage;
return new
{
field = ToCamelCase(e.PropertyName),
code = valCode,
message = valMsg
};
}).ToList();
var envelope = new
{
success = false,
code = headerCode,
message = headerMsg,
data = (object?)null,
errors = fieldErrors,
traceId = Activity.Current?.Id ?? ctx.TraceIdentifier,
timestamp = DateTimeOffset.UtcNow,
};
ctx.Response.StatusCode = StatusCodes.Status400BadRequest;
ctx.Response.ContentType = "application/json";
await JsonSerializer.SerializeAsync(ctx.Response.Body, envelope, JsonOptions)
.ConfigureAwait(false);
}
private static string ToCamelCase(string name)
{
if (string.IsNullOrEmpty(name)) return name;
return char.ToLowerInvariant(name[0]) + name[1..];
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
};
}