From 5589ab9aac95776d34d3c4d744ed060dee546e40 Mon Sep 17 00:00:00 2001 From: Marco Minerva Date: Wed, 12 Apr 2023 08:30:32 +0200 Subject: [PATCH] Use Error property when throwing exception (#1448) * Use Error property when throwing exception #1376 * Add Unit test * Update test assertions --- Refit.Tests/ResponseTests.cs | 38 ++++++++++++++++++++++++++++++++++++ Refit/ApiResponse.cs | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Refit.Tests/ResponseTests.cs b/Refit.Tests/ResponseTests.cs index 85ea11c82..73798fe54 100644 --- a/Refit.Tests/ResponseTests.cs +++ b/Refit.Tests/ResponseTests.cs @@ -116,6 +116,44 @@ public async Task ThrowsValidationException() Assert.Equal("title", actualException.Content.Title); Assert.Equal("type", actualException.Content.Type); } + + /// + /// Test to verify if EnsureSuccessStatusCodeAsync throws a ValidationApiException for a Bad Request in terms of RFC 7807 + /// + [Fact] + public async Task When_BadRequest_EnsureSuccessStatusCodeAsync_ThrowsValidationException() + { + var expectedContent = new ProblemDetails + { + Detail = "detail", + Errors = { { "Field1", new string[] { "Problem1" } }, { "Field2", new string[] { "Problem2" } } }, + Instance = "instance", + Status = 1, + Title = "title", + Type = "type" + }; + + var expectedResponse = new HttpResponseMessage(HttpStatusCode.BadRequest) + { + Content = new StringContent(JsonConvert.SerializeObject(expectedContent)) + }; + + expectedResponse.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/problem+json"); + mockHandler.Expect(HttpMethod.Get, "http://api/GetApiResponseTestObject") + .Respond(req => expectedResponse); + + using var response = await fixture.GetApiResponseTestObject(); + var actualException = await Assert.ThrowsAsync(() => response.EnsureSuccessStatusCodeAsync()); + + Assert.NotNull(actualException.Content); + Assert.Equal("detail", actualException.Content.Detail); + Assert.Equal("Problem1", actualException.Content.Errors["Field1"][0]); + Assert.Equal("Problem2", actualException.Content.Errors["Field2"][0]); + Assert.Equal("instance", actualException.Content.Instance); + Assert.Equal(1, actualException.Content.Status); + Assert.Equal("title", actualException.Content.Title); + Assert.Equal("type", actualException.Content.Type); + } [Fact] public async Task WhenProblemDetailsResponseContainsExtensions_ShouldHydrateExtensions() diff --git a/Refit/ApiResponse.cs b/Refit/ApiResponse.cs index daa6e803b..6e8496c08 100644 --- a/Refit/ApiResponse.cs +++ b/Refit/ApiResponse.cs @@ -86,7 +86,7 @@ public async Task> EnsureSuccessStatusCodeAsync() { if (!IsSuccessStatusCode) { - var exception = await ApiException.Create(response.RequestMessage!, response.RequestMessage!.Method, response, Settings).ConfigureAwait(false); + var exception = Error ?? await ApiException.Create(response.RequestMessage!, response.RequestMessage!.Method, response, Settings).ConfigureAwait(false); Dispose();