Update jsonrpc4net
[CSharpForFun/.git] / jsonrpc4net / jsonrpc4net / ExceptionResolver.cs
1 using Newtonsoft.Json.Linq;
2 using System;
3 using System.Collections.Generic;
4
5 namespace GumartinM.JsonRPC4NET
6 {
7         /// <summary>
8         /// Exception resolver.
9         /// </summary>
10     public class ExceptionResolver
11     {
12         /// <summary>
13         /// Resolves the exception.
14         /// </summary>
15         /// <returns>The exception.</returns>
16         /// <param name="errorToken">Error token.</param>
17         public Exception ResolveException(JToken errorToken)
18         {
19             JObject errorData = (JObject)errorToken;
20             IDictionary<string, JToken> errorTokens = errorData;
21
22             if (!errorTokens.ContainsKey("data"))
23             {
24                 return CreateJsonRpcClientException(errorToken);
25             }
26
27             JToken dataToken = errorToken["data"];
28             JObject data = (JObject)dataToken;
29             errorTokens = data;
30
31             if (!errorTokens.ContainsKey("exceptionTypeName"))
32             {
33                 return CreateJsonRpcClientException(errorToken);
34             }
35
36             string exceptionTypeName = data["exceptionTypeName"].Value<string>();
37             string message = data.Value<string>("message");
38
39             Exception endException = CreateException(exceptionTypeName, message);
40
41             return endException;
42         }
43
44         /// <summary>
45         /// Creates the json rpc client exception.
46         /// </summary>
47         /// <returns>The json rpc client exception.</returns>
48         /// <param name="errorToken">Error token.</param>
49         private JsonRpcClientException CreateJsonRpcClientException(JToken errorToken)
50         {
51             return new JsonRpcClientException(
52               errorToken.Value<int?>("code") ?? 0,
53               errorToken.Value<string>("message"),
54               errorToken["data"]);
55         }
56
57         /// <summary>
58         /// Creates the exception.
59         /// </summary>
60         /// <returns>The exception.</returns>
61         /// <param name="exceptionTypeName">Exception type name.</param>
62         /// <param name="message">Message.</param>
63         private Exception CreateException(string exceptionTypeName, string message)
64         {
65             return new Exception("Remote exception: " + exceptionTypeName +
66                                  " Remote message: " + message);
67         }
68     }
69 }