/
DefaultExceptionToErrorInfoConverter.cs
323 lines (263 loc) · 10.9 KB
/
DefaultExceptionToErrorInfoConverter.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
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Volo.Abp.Authorization;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Entities;
using Volo.Abp.ExceptionHandling;
using Volo.Abp.ExceptionHandling.Localization;
using Volo.Abp.Http;
using Volo.Abp.Http.Client;
using Volo.Abp.Localization;
using Volo.Abp.Localization.ExceptionHandling;
using Volo.Abp.Validation;
namespace Volo.Abp.AspNetCore.ExceptionHandling;
public class DefaultExceptionToErrorInfoConverter : IExceptionToErrorInfoConverter, ITransientDependency
{
protected AbpExceptionLocalizationOptions LocalizationOptions { get; }
protected IStringLocalizerFactory StringLocalizerFactory { get; }
protected IStringLocalizer<AbpExceptionHandlingResource> L { get; }
protected IServiceProvider ServiceProvider { get; }
public DefaultExceptionToErrorInfoConverter(
IOptions<AbpExceptionLocalizationOptions> localizationOptions,
IStringLocalizerFactory stringLocalizerFactory,
IStringLocalizer<AbpExceptionHandlingResource> stringLocalizer,
IServiceProvider serviceProvider)
{
ServiceProvider = serviceProvider;
StringLocalizerFactory = stringLocalizerFactory;
L = stringLocalizer;
LocalizationOptions = localizationOptions.Value;
}
public RemoteServiceErrorInfo Convert(Exception exception, bool includeSensitiveDetails)
{
var exceptionHandlingOptions = CreateDefaultOptions();
exceptionHandlingOptions.SendExceptionsDetailsToClients = includeSensitiveDetails;
exceptionHandlingOptions.SendStackTraceToClients = includeSensitiveDetails;
var errorInfo = CreateErrorInfoWithoutCode(exception, exceptionHandlingOptions);
if (exception is IHasErrorCode hasErrorCodeException)
{
errorInfo.Code = hasErrorCodeException.Code;
}
return errorInfo;
}
public RemoteServiceErrorInfo Convert(Exception exception, Action<AbpExceptionHandlingOptions>? options = null)
{
var exceptionHandlingOptions = CreateDefaultOptions();
options?.Invoke(exceptionHandlingOptions);
var errorInfo = CreateErrorInfoWithoutCode(exception, exceptionHandlingOptions);
if (exception is IHasErrorCode hasErrorCodeException)
{
errorInfo.Code = hasErrorCodeException.Code;
}
return errorInfo;
}
protected virtual RemoteServiceErrorInfo CreateErrorInfoWithoutCode(Exception exception, AbpExceptionHandlingOptions options)
{
if (options.SendExceptionsDetailsToClients)
{
return CreateDetailedErrorInfoFromException(exception, options.SendStackTraceToClients);
}
exception = TryToGetActualException(exception);
if (exception is AbpRemoteCallException remoteCallException && remoteCallException.Error != null)
{
return remoteCallException.Error;
}
if (exception is AbpDbConcurrencyException)
{
return new RemoteServiceErrorInfo(L["AbpDbConcurrencyErrorMessage"]);
}
if (exception is EntityNotFoundException)
{
return CreateEntityNotFoundError((exception as EntityNotFoundException)!);
}
var errorInfo = new RemoteServiceErrorInfo();
if (exception is IUserFriendlyException || exception is AbpRemoteCallException)
{
errorInfo.Message = exception.Message;
errorInfo.Details = (exception as IHasErrorDetails)?.Details;
}
if (exception is IHasValidationErrors)
{
if (errorInfo.Message.IsNullOrEmpty())
{
errorInfo.Message = L["ValidationErrorMessage"];
}
if (errorInfo.Details.IsNullOrEmpty())
{
errorInfo.Details = GetValidationErrorNarrative((exception as IHasValidationErrors)!);
}
errorInfo.ValidationErrors = GetValidationErrorInfos((exception as IHasValidationErrors)!);
}
TryToLocalizeExceptionMessage(exception, errorInfo);
if (errorInfo.Message.IsNullOrEmpty())
{
errorInfo.Message = L["InternalServerErrorMessage"];
}
errorInfo.Data = exception.Data;
return errorInfo;
}
protected virtual void TryToLocalizeExceptionMessage(Exception exception, RemoteServiceErrorInfo errorInfo)
{
if (exception is ILocalizeErrorMessage localizeErrorMessageException)
{
using (var scope = ServiceProvider.CreateScope())
{
errorInfo.Message = localizeErrorMessageException.LocalizeMessage(new LocalizationContext(scope.ServiceProvider));
}
return;
}
if (!(exception is IHasErrorCode exceptionWithErrorCode))
{
return;
}
if (exceptionWithErrorCode.Code.IsNullOrWhiteSpace() ||
!exceptionWithErrorCode.Code!.Contains(":"))
{
return;
}
var codeNamespace = exceptionWithErrorCode.Code.Split(':')[0];
var localizationResourceType = LocalizationOptions.ErrorCodeNamespaceMappings.GetOrDefault(codeNamespace);
if (localizationResourceType == null)
{
return;
}
var stringLocalizer = StringLocalizerFactory.Create(localizationResourceType);
var localizedString = stringLocalizer[exceptionWithErrorCode.Code];
if (localizedString.ResourceNotFound)
{
return;
}
var localizedValue = localizedString.Value;
if (exception.Data != null && exception.Data.Count > 0)
{
foreach (var key in exception.Data.Keys)
{
localizedValue = localizedValue.Replace("{" + key + "}", exception.Data[key]?.ToString());
}
}
errorInfo.Message = localizedValue;
}
protected virtual RemoteServiceErrorInfo CreateEntityNotFoundError(EntityNotFoundException exception)
{
if (exception.EntityType != null)
{
return new RemoteServiceErrorInfo(
string.Format(
L["EntityNotFoundErrorMessage"],
exception.EntityType.Name,
exception.Id
)
);
}
return new RemoteServiceErrorInfo(exception.Message);
}
protected virtual Exception TryToGetActualException(Exception exception)
{
if (exception is AggregateException aggException && aggException.InnerException != null)
{
if (aggException.InnerException is AbpValidationException ||
aggException.InnerException is AbpAuthorizationException ||
aggException.InnerException is EntityNotFoundException ||
aggException.InnerException is IBusinessException)
{
return aggException.InnerException;
}
}
return exception;
}
protected virtual RemoteServiceErrorInfo CreateDetailedErrorInfoFromException(Exception exception, bool sendStackTraceToClients)
{
var detailBuilder = new StringBuilder();
AddExceptionToDetails(exception, detailBuilder, sendStackTraceToClients);
var errorInfo = new RemoteServiceErrorInfo(exception.Message, detailBuilder.ToString(), data: exception.Data);
if (exception is AbpValidationException)
{
errorInfo.ValidationErrors = GetValidationErrorInfos((exception as AbpValidationException)!);
}
return errorInfo;
}
protected virtual void AddExceptionToDetails(Exception exception, StringBuilder detailBuilder, bool sendStackTraceToClients)
{
//Exception Message
detailBuilder.AppendLine(exception.GetType().Name + ": " + exception.Message);
//Additional info for UserFriendlyException
if (exception is IUserFriendlyException &&
exception is IHasErrorDetails)
{
var details = ((IHasErrorDetails)exception).Details;
if (!details.IsNullOrEmpty())
{
detailBuilder.AppendLine(details);
}
}
//Additional info for AbpValidationException
if (exception is AbpValidationException validationException)
{
if (validationException.ValidationErrors.Count > 0)
{
detailBuilder.AppendLine(GetValidationErrorNarrative(validationException));
}
}
//Exception StackTrace
if (sendStackTraceToClients && !string.IsNullOrEmpty(exception.StackTrace))
{
detailBuilder.AppendLine("STACK TRACE: " + exception.StackTrace);
}
//Inner exception
if (exception.InnerException != null)
{
AddExceptionToDetails(exception.InnerException, detailBuilder, sendStackTraceToClients);
}
//Inner exceptions for AggregateException
if (exception is AggregateException aggException)
{
if (aggException.InnerExceptions.IsNullOrEmpty())
{
return;
}
foreach (var innerException in aggException.InnerExceptions)
{
AddExceptionToDetails(innerException, detailBuilder, sendStackTraceToClients);
}
}
}
protected virtual RemoteServiceValidationErrorInfo[] GetValidationErrorInfos(IHasValidationErrors validationException)
{
var validationErrorInfos = new List<RemoteServiceValidationErrorInfo>();
foreach (var validationResult in validationException.ValidationErrors)
{
var validationError = new RemoteServiceValidationErrorInfo(validationResult.ErrorMessage!);
if (validationResult.MemberNames != null && validationResult.MemberNames.Any())
{
validationError.Members = validationResult.MemberNames.Select(m => m.ToCamelCase()).ToArray();
}
validationErrorInfos.Add(validationError);
}
return validationErrorInfos.ToArray();
}
protected virtual string GetValidationErrorNarrative(IHasValidationErrors validationException)
{
var detailBuilder = new StringBuilder();
detailBuilder.AppendLine(L["ValidationNarrativeErrorMessageTitle"]);
foreach (var validationResult in validationException.ValidationErrors)
{
detailBuilder.AppendFormat(" - {0}", validationResult.ErrorMessage);
detailBuilder.AppendLine();
}
return detailBuilder.ToString();
}
protected virtual AbpExceptionHandlingOptions CreateDefaultOptions()
{
return new AbpExceptionHandlingOptions
{
SendExceptionsDetailsToClients = false,
SendStackTraceToClients = true
};
}
}