-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPCError.cs
118 lines (105 loc) · 2.9 KB
/
RPCError.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
namespace jsonrpc;
using System;
public enum RPCErrorCode
{
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603,
ServerError = 32000,
NetworkError = 32001
}
public class RPCError
{
public RPCErrorCode Code
{
get; private set;
}
public string? Message
{
get; private set;
}
public object? Data
{
get; private set;
}
public RPCError(RPCErrorCode code, string message, object? data = null)
{
Code = code;
Message = message;
Data = data;
}
public RPCError() : this(RPCErrorCode.ServerError, "Server error")
{
}
public RPCError(RPCErrorCode code) : this(code, GetDefaultErrorMessage(code))
{
}
public RPCError(Dictionary<string, object>? errorDict)
{
var errorCode = Convert.ToInt32(value: errorDict["code"].ToString());
var errorMessage = Convert.ToString(errorDict["message"]);
var errorData = errorDict.TryGetValue("data", out var value) ? value : null;
Code = (RPCErrorCode)errorCode;
Message = errorMessage;
Data = errorData;
}
public override string ToString()
{
if (Data != null)
{
return $"RPCError: {Message} ({Code}): {Data}.";
}
else
{
return $"RPCError: {Message} ({Code}).";
}
}
public static RPCError ErrorWithCode(RPCErrorCode code)
{
return new RPCError(code);
}
public static RPCError? ErrorWithDictionary(Dictionary<string, object> dictionary)
{
if (dictionary.TryGetValue("code", out var codeObj) && dictionary.TryGetValue("message", out var messageObj))
{
var code = Convert.ToInt32(codeObj);
var message = Convert.ToString(messageObj);
object? data;
if (dictionary.TryGetValue("data", out var value))
{
data = value as object;
}
else
{
data = null;
}
return new RPCError((RPCErrorCode)code, message ?? "", data);
}
else
{
return null;
}
}
private static string GetDefaultErrorMessage(RPCErrorCode code)
{
switch (code)
{
case RPCErrorCode.ParseError:
return "Parse error";
case RPCErrorCode.InvalidRequest:
return "Invalid Request";
case RPCErrorCode.MethodNotFound:
return "Method not found";
case RPCErrorCode.InvalidParams:
return "Invalid params";
case RPCErrorCode.InternalError:
return "Internal error";
case RPCErrorCode.NetworkError:
return "Network error";
default:
return "Server error";
}
}
}