Skip to content

Commit 5060ff7

Browse files
authored
Merge pull request #151 from mwarzybok-sumoheavy/feature/SP-874
SP-874 Support "errors" array
2 parents 3fe5284 + 9aefe78 commit 5060ff7

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

BitPay/Clients/HttpResponseParser.cs

+34
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,40 @@ public static async Task<string> ResponseToJsonString(HttpResponseMessage? respo
7979
BitPayExceptionProvider.ThrowApiExceptionWithMessage(value!.ToString(), code!.ToString());
8080
}
8181

82+
#pragma warning disable CA1865
83+
if (jObj.TryGetValue("errors", out value))
84+
{
85+
var finalMessage = "";
86+
foreach (var errorItem in value.Children().ToList())
87+
{
88+
JObject jObjectErrorItem = (JObject)errorItem;
89+
string errorValue = (string) (jObjectErrorItem.ContainsKey("error") ? errorItem["error"] : "")!;
90+
string paramValue = (string) (jObjectErrorItem.ContainsKey("param") ? errorItem["param"] : "")!;
91+
92+
if (errorValue.EndsWith(".", System.StringComparison.Ordinal))
93+
{
94+
errorValue = errorValue.Substring(0, errorValue.Length - 1);
95+
}
96+
97+
string errorMessage = $"{errorValue} {paramValue}".Trim();
98+
99+
if (!errorMessage.EndsWith(".", System.StringComparison.Ordinal))
100+
{
101+
errorMessage += ".";
102+
}
103+
104+
if (finalMessage.Length > 0)
105+
{
106+
errorMessage = " " + errorMessage;
107+
}
108+
109+
finalMessage += errorMessage;
110+
}
111+
112+
BitPayExceptionProvider.ThrowApiExceptionWithMessage(finalMessage);
113+
}
114+
#pragma warning restore CA1865
115+
82116
if (jObj.ContainsKey("status") && jObj.ContainsKey("data"))
83117
{
84118
if(jObj.TryGetValue("data", out value))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Copyright (c) 2019 BitPay.
2+
// All rights reserved.
3+
4+
using System.Net;
5+
using System.Net.Http;
6+
7+
using BitPay.Clients;
8+
using BitPay.Exceptions;
9+
10+
using Xunit;
11+
12+
namespace BitPayUnitTest.Clients
13+
{
14+
public class HttpResponseParserTest
15+
{
16+
[Fact]
17+
public void it_should_throws_bitpay_api_exception_for_response_with_errors()
18+
{
19+
HttpResponseMessage responseMessage = new HttpResponseMessage
20+
{
21+
StatusCode = HttpStatusCode.OK,
22+
Content = new StringContent(
23+
"{\"errors\":[{\"error\":\"Missing required parameter.\",\"param\":\"price\"},{\"error\":\"Missing required parameter.\",\"param\":\"currency\"}]}"),
24+
RequestMessage = new HttpRequestMessage(HttpMethod.Post, "any")
25+
};
26+
27+
var exception =
28+
Assert.ThrowsAsync<BitPayApiException>(() => HttpResponseParser.ResponseToJsonString(responseMessage))
29+
.Result;
30+
Assert.Equal("Missing required parameter price. Missing required parameter currency.", exception.Message);
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)