-
Notifications
You must be signed in to change notification settings - Fork 2
/
Extensions.Exception.cs
276 lines (251 loc) · 10.2 KB
/
Extensions.Exception.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
#region Related components
using System;
using System.Net;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WampSharp.V2.Core.Contracts;
using net.vieapps.Components.Utility;
#endregion
namespace net.vieapps.Services
{
public static partial class Extensions
{
/// <summary>
/// Gets the stack trace of the error exception
/// </summary>
/// <param name="exception">The exception to get the stack</param>
/// <param name="onlyStack">true to get only stack trace when the exception is <see cref="WampException">WampException</see></param>
/// <returns>The string that presents the stack trace</returns>
public static string GetStack(this Exception exception, bool onlyStack = true, RequestInfo requestInfo = null)
{
var stack = "";
if (exception is WampException wampException)
{
if (wampException.Details != null && wampException.Details.Count == 7)
{
stack = wampException.Details["Stack"] as string;
if (!onlyStack)
{
var innerStack = wampException.Details["InnerStack"] as string;
stack += string.IsNullOrWhiteSpace(innerStack) ? "" : "\r\n" + innerStack;
}
}
else
{
var wampDetails = wampException.GetDetails(requestInfo);
stack = wampDetails.Item6 != null
? (onlyStack ? wampDetails.Item6.Get<string>("Stack") : wampDetails.Item6.ToString(Formatting.Indented))?.Replace("\\r", "\r").Replace("\\n", "\n").Replace(@"\\", @"\")
: wampDetails.Item4?.Replace("\\r", "\r")?.Replace("\\n", "\n")?.Replace(@"\\", @"\");
}
}
else if (exception != null)
{
stack = exception.StackTrace;
var inner = onlyStack ? null : exception.InnerException;
var counter = 0;
while (inner != null)
{
counter++;
stack += "\r\n" + $"--- Inner ({counter}): ---------------------- " + "\r\n" + $"> Message: {inner.Message}\r\n" + $"> Type: {inner.GetType()}\r\n" + inner.StackTrace;
inner = inner.InnerException;
}
}
return stack;
}
/// <summary>
/// Gets the details of the WAMP exception
/// </summary>
/// <param name="wampException"></param>
/// <param name="requestInfo"></param>
/// <returns></returns>
public static Tuple<int, string, string, string, Exception, JObject> GetDetails(this WampException wampException, RequestInfo requestInfo = null)
{
string message = "", type = "", stack = "";
JObject innerJson = null;
// unavailable
if (wampException.ErrorUri.Equals("wamp.error.no_such_procedure") || wampException.ErrorUri.Equals("wamp.error.no_such_registration") || wampException.ErrorUri.Equals("wamp.error.callee_unregistered"))
{
if (wampException.Arguments != null && wampException.Arguments.Length > 0 && wampException.Arguments[0] != null && wampException.Arguments[0] is JValue msg)
{
message = $"{msg.Value}";
var start = message.IndexOf("'") + 1;
var end = message.IndexOf("'", start);
message = $"The service ({message.Substring(start, end - start).Replace("'", "")}) is unavailable";
}
else
message = "The service is unavailable";
type = "ServiceUnavailableException";
stack = wampException.StackTrace;
}
// cannot serialize
else if (wampException.ErrorUri.Equals("wamp.error.invalid_argument"))
{
message = "Cannot serialize or deserialize one of arguments, all arguments must be instance of a serializable class - interfaces are not be deserialized";
if (wampException.Arguments != null && wampException.Arguments.Length > 0 && wampException.Arguments[0] != null && wampException.Arguments[0] is JValue msg)
message += $" => {msg.Value}";
type = "SerializationException";
stack = wampException.StackTrace;
}
// runtime error
else if (wampException.ErrorUri.Equals("wamp.error.runtime_error"))
{
if (wampException.Details != null && wampException.Details.Count == 7)
{
message = wampException.Details["Message"] as string;
var innerStack = wampException.Details["InnerStack"] as string;
stack = $"{wampException.Details["Stack"]}{(string.IsNullOrWhiteSpace(innerStack) ? "" : $"\r\n{innerStack}")}";
innerJson = wampException.Details["InnerJson"] as JObject;
type = wampException.Details["Type"] as string ?? "ServiceOperationException";
}
else
{
var firstArgument = wampException.Arguments?.First();
var infoJson = firstArgument != null && firstArgument is JObject jinfo ? jinfo : null;
var infoValue = firstArgument != null && firstArgument is JValue vinfo ? vinfo : null;
var requestJson = wampException.Arguments != null && wampException.Arguments.Length > 2 && wampException.Arguments[2] != null && wampException.Arguments[2] is JObject jrequest ? jrequest : null;
var exceptionJson = wampException.Arguments != null && wampException.Arguments.Length > 4 && wampException.Arguments[4] != null && wampException.Arguments[4] is JObject jexception ? jexception : null;
if (infoJson != null)
foreach (var info in infoJson)
{
var infoVal = info.Value != null && info.Value is JValue jval ? jval : null;
if (infoVal != null && infoVal.Value != null)
stack += (stack.Equals("") ? "" : "\r\n" + $"----- Inner ({info.Key}) --------------------" + "\r\n")
+ infoVal.Value.ToString();
}
else if (infoValue != null)
stack = wampException.StackTrace;
var serviceName = "unknown";
if (requestInfo != null)
serviceName = requestInfo.ServiceName;
else if (requestJson != null)
{
var info = requestJson.First;
if (info != null && info is JProperty jprop && jprop.Name.Equals("RequestInfo") && jprop.Value != null && jprop.Value is JObject jobj)
serviceName = jobj.As<RequestInfo>()?.ServiceName ?? "unknown";
}
innerJson = exceptionJson?.GetJsonException();
message = innerJson?.Get<string>("Message") ?? infoValue?.Value?.ToString() ?? $"Error occurred at \"services.{serviceName.ToLower()}\"";
type = innerJson?.Get<JValue>("Type")?.Value?.ToString()?.ToArray('.').Last() ?? "ServiceOperationException";
}
}
// unknown
else
{
message = wampException.Message;
type = wampException.GetTypeName(true);
stack = wampException.StackTrace;
}
return new Tuple<int, string, string, string, Exception, JObject>(type.GetErrorCode(), message, type, stack, wampException.InnerException, innerJson);
}
static int GetErrorCode(this string type)
{
switch (type)
{
case "MethodNotAllowedException":
return (int)HttpStatusCode.MethodNotAllowed;
case "NotImplementedException":
return (int)HttpStatusCode.NotImplemented;
case "AccessDeniedException":
return (int)HttpStatusCode.Forbidden;
case "UnauthorizedException":
return (int)HttpStatusCode.Unauthorized;
default:
if (type.Contains("Invalid"))
return (int)HttpStatusCode.BadRequest;
if (type.Equals("ServiceNotFoundException") || type.Contains("Unavailable"))
return (int)HttpStatusCode.ServiceUnavailable;
if (type.EndsWith("NotFoundException"))
return (int)HttpStatusCode.NotFound;
return (int)HttpStatusCode.InternalServerError;
}
}
static JObject GetJsonException(this JToken exception)
{
var json = new JObject
{
{ "Message", exception["Message"] },
{ "Type", exception["ClassName"] },
{ "StackTrace", exception["StackTraceString"] },
{ "Method", exception["ExceptionMethod"] },
{ "Source", exception["Source"] }
};
var inner = exception["InnerException"];
if (inner != null && inner is JObject)
json["InnerException"] = inner.GetJsonException();
return json;
}
/// <summary>
/// Gets the runtime exception to throw
/// </summary>
/// <param name="requestInfo"></param>
/// <param name="exception"></param>
/// <param name="message"></param>
/// <param name="onCompleted"></param>
/// <returns></returns>
public static WampException GetRuntimeException(this RequestInfo requestInfo, Exception exception, string message = null, Action<string, Exception> onCompleted = null)
{
// normalize exception
exception = exception is RepositoryOperationException
? exception.InnerException
: exception;
// prepare message
message = exception != null
? string.IsNullOrWhiteSpace(message) ? exception.Message : $"{message} => {exception.Message}"
: message ?? "Error occurred while processing";
// pre-process
onCompleted?.Invoke(message, exception);
// return the exception
if (exception is WampException wampException)
{
if (wampException.ErrorUri.Equals("wamp.error.runtime_error") && wampException.Details != null && wampException.Details.Count == 7)
return wampException;
var wampDetails = wampException.GetDetails(requestInfo);
var innerStack = "";
var innerException = wampException?.InnerException;
var counter = 0;
while (innerException != null)
{
counter++;
innerStack += (innerStack != "" ? "\r\n" : "") + $"--- Inner ({counter}): ---------------------- \r\n{innerException.StackTrace}";
innerException = innerException.InnerException;
}
var details = new Dictionary<string, object>
{
["Code"] = wampDetails.Item1,
["Message"] = wampDetails.Item2,
["Type"] = wampDetails.Item3,
["Stack"] = wampDetails.Item4,
["InnerStack"] = innerStack,
["InnerJson"] = wampDetails.Item6,
["RequestInfo"] = requestInfo.ToJson()
};
return new WampException(details, wampException.ErrorUri, new object[0]);
}
else
{
var innerStack = "";
var innerException = exception?.InnerException;
var counter = 0;
while (innerException != null)
{
counter++;
innerStack += (innerStack != "" ? "\r\n" : "") + $"--- Inner ({counter}): ---------------------- \r\n{innerException.StackTrace}";
innerException = innerException.InnerException;
}
var details = new Dictionary<string, object>
{
["Code"] = (exception?.GetTypeName(true) ?? "").GetErrorCode(),
["Message"] = message,
["Type"] = exception?.GetTypeName(true) ?? "ServiceOperationException",
["Stack"] = exception?.StackTrace,
["InnerStack"] = innerStack,
["InnerJson"] = null,
["RequestInfo"] = requestInfo.ToJson()
};
return new WampException(details, "wamp.error.runtime_error", Array.Empty<object>());
}
}
}
}