Skip to content

Commit 944a6f0

Browse files
committed
Add JTokenExtensions.ThrowIfHasErrors
1 parent 28cbcdd commit 944a6f0

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

RedditSharp/Exceptions/RedditException.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using Newtonsoft.Json.Linq;
23

34
namespace RedditSharp
45
{
@@ -8,6 +9,8 @@ namespace RedditSharp
89
[Serializable]
910
public class RedditException : Exception
1011
{
12+
public JArray Errors { get; }
13+
1114
/// <summary>
1215
/// Initializes a new instance of the RedditException class.
1316
/// </summary>
@@ -26,6 +29,17 @@ public RedditException(string message)
2629

2730
}
2831

32+
/// <summary>
33+
/// Initializes a new instance of the RedditException class with a specified error message and a JArray of errors
34+
/// </summary>
35+
/// <param name="message">The message that describes the error.</param>
36+
/// <param name="errors">List of errors.</param>
37+
public RedditException(string message, JArray errors)
38+
: base(message)
39+
{
40+
Errors = errors;
41+
}
42+
2943
/// <summary>
3044
/// Initializes a new instance of the RedditException class with a specified error message and
3145
/// a referenced inner exception that is the cause of this exception.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
using Newtonsoft.Json.Linq;
2+
3+
namespace RedditSharp.Extensions.JTokenExtensions
4+
{
5+
public static class JTokenExtensions
6+
{
7+
public static void ThrowIfHasErrors(this JToken json, string message)
8+
{
9+
if (json["errors"].IsNonEmptyArray(out var errors))
10+
{
11+
throw new RedditException($"{message} {errors}", errors);
12+
}
13+
}
14+
15+
public static bool IsNonEmptyArray(this JToken json, out JArray array)
16+
{
17+
var isArray = _IsArray(json, out array);
18+
return isArray && array.Count > 0;
19+
}
20+
21+
private static bool _IsArray(JToken json, out JArray array)
22+
{
23+
if (json != null && json.Type == JTokenType.Array)
24+
{
25+
array = (JArray)json;
26+
return true;
27+
}
28+
array = default;
29+
return false;
30+
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)