Skip to content

Commit

Permalink
Merge pull request #151 from mwarzybok-sumoheavy/feature/SP-874
Browse files Browse the repository at this point in the history
SP-874 Support "errors" array
  • Loading branch information
bobbrodie committed Feb 29, 2024
2 parents 3fe5284 + 9aefe78 commit 5060ff7
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
34 changes: 34 additions & 0 deletions BitPay/Clients/HttpResponseParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,40 @@ public static async Task<string> ResponseToJsonString(HttpResponseMessage? respo
BitPayExceptionProvider.ThrowApiExceptionWithMessage(value!.ToString(), code!.ToString());
}

#pragma warning disable CA1865
if (jObj.TryGetValue("errors", out value))
{
var finalMessage = "";
foreach (var errorItem in value.Children().ToList())
{
JObject jObjectErrorItem = (JObject)errorItem;
string errorValue = (string) (jObjectErrorItem.ContainsKey("error") ? errorItem["error"] : "")!;
string paramValue = (string) (jObjectErrorItem.ContainsKey("param") ? errorItem["param"] : "")!;

if (errorValue.EndsWith(".", System.StringComparison.Ordinal))
{
errorValue = errorValue.Substring(0, errorValue.Length - 1);
}

string errorMessage = $"{errorValue} {paramValue}".Trim();

if (!errorMessage.EndsWith(".", System.StringComparison.Ordinal))
{
errorMessage += ".";
}

if (finalMessage.Length > 0)
{
errorMessage = " " + errorMessage;
}

finalMessage += errorMessage;
}

BitPayExceptionProvider.ThrowApiExceptionWithMessage(finalMessage);
}
#pragma warning restore CA1865

if (jObj.ContainsKey("status") && jObj.ContainsKey("data"))
{
if(jObj.TryGetValue("data", out value))
Expand Down
33 changes: 33 additions & 0 deletions BitPayUnitTest/Clients/HttpResponseParserTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) 2019 BitPay.
// All rights reserved.

using System.Net;
using System.Net.Http;

using BitPay.Clients;
using BitPay.Exceptions;

using Xunit;

namespace BitPayUnitTest.Clients
{
public class HttpResponseParserTest
{
[Fact]
public void it_should_throws_bitpay_api_exception_for_response_with_errors()
{
HttpResponseMessage responseMessage = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(
"{\"errors\":[{\"error\":\"Missing required parameter.\",\"param\":\"price\"},{\"error\":\"Missing required parameter.\",\"param\":\"currency\"}]}"),
RequestMessage = new HttpRequestMessage(HttpMethod.Post, "any")
};

var exception =
Assert.ThrowsAsync<BitPayApiException>(() => HttpResponseParser.ResponseToJsonString(responseMessage))
.Result;
Assert.Equal("Missing required parameter price. Missing required parameter currency.", exception.Message);
}
}
}

0 comments on commit 5060ff7

Please sign in to comment.