forked from JohnnyCrazy/SpotifyAPI-NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIException.cs
More file actions
76 lines (66 loc) · 1.74 KB
/
APIException.cs
File metadata and controls
76 lines (66 loc) · 1.74 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
using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SpotifyAPI.Web.Http;
namespace SpotifyAPI.Web
{
[Serializable]
public class APIException : Exception
{
public IResponse? Response { get; set; }
public APIException(IResponse response) : base(ParseAPIErrorMessage(response))
{
Ensure.ArgumentNotNull(response, nameof(response));
Response = response;
}
public APIException()
{
}
public APIException(string message) : base(message)
{
}
public APIException(string message, Exception innerException) : base(message, innerException)
{
}
protected APIException(SerializationInfo info, StreamingContext context) : base(info, context)
{
Response = info.GetValue("APIException.Response", typeof(IResponse)) as IResponse;
}
private static string? ParseAPIErrorMessage(IResponse response)
{
var body = response.Body as string;
if (string.IsNullOrEmpty(body))
{
return null;
}
try
{
JObject bodyObject = JObject.Parse(body!);
var error = bodyObject.Value<JToken>("error");
if (error == null)
{
return null;
}
else if (error.Type == JTokenType.String)
{
return error.ToString();
}
else if (error.Type == JTokenType.Object)
{
return error.Value<string>("message");
}
}
catch (JsonReaderException)
{
return null;
}
return null;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("APIException.Response", Response);
}
}
}