Skip to content

Commit

Permalink
[csharp-netcore][httpclient] Issues managing error statuses (OpenAPIT…
Browse files Browse the repository at this point in the history
…ools#9389)

* [csharp-netcore] correct rawContent read

* [csharp-netcore] avoid deserialize result when in error

* [csharp-netcore] avoid aggregate exceptions

* Updated samples

* Updated samples

* Refactored PetApiTest

* Updated samples

* Fixed test issues

* reverted previous commit
  • Loading branch information
lucamazzanti authored May 6, 2021
1 parent f4f4d5d commit 2f2e250
Show file tree
Hide file tree
Showing 5 changed files with 652 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,13 @@ namespace {{packageName}}.Client
if (type == typeof(byte[])) // return byte array
{
return response.Content.ReadAsByteArrayAsync().Result;
return response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
}

// TODO: ? if (type.IsAssignableFrom(typeof(Stream)))
if (type == typeof(Stream))
{
var bytes = response.Content.ReadAsByteArrayAsync().Result;
var bytes = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
if (headers != null)
{
var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath)
Expand All @@ -128,18 +128,18 @@ namespace {{packageName}}.Client

if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
{
return DateTime.Parse(response.Content.ReadAsStringAsync().Result, null, System.Globalization.DateTimeStyles.RoundtripKind);
return DateTime.Parse(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), null, System.Globalization.DateTimeStyles.RoundtripKind);
}

if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
{
return Convert.ChangeType(response.Content.ReadAsStringAsync().Result, type);
return Convert.ChangeType(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type);
}

// at this point, it must be a model (json)
try
{
return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result, type, _serializerSettings);
return JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), type, _serializerSettings);
}
catch (Exception e)
{
Expand Down Expand Up @@ -401,10 +401,10 @@ namespace {{packageName}}.Client
partial void InterceptRequest(HttpRequestMessage req);
partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response);

private ApiResponse<T> ToApiResponse<T>(HttpResponseMessage response, object responseData, Uri uri)
private async Task<ApiResponse<T>> ToApiResponse<T>(HttpResponseMessage response, object responseData, Uri uri)
{
T result = (T) responseData;
string rawContent = response.Content.ToString();
string rawContent = await response.Content.ReadAsStringAsync();
var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent)
{
Expand Down Expand Up @@ -446,7 +446,7 @@ namespace {{packageName}}.Client

private ApiResponse<T> Exec<T>(HttpRequestMessage req, IReadableConfiguration configuration)
{
return ExecAsync<T>(req, configuration).Result;
return ExecAsync<T>(req, configuration).GetAwaiter().GetResult();
}

private async Task<ApiResponse<T>> ExecAsync<T>(HttpRequestMessage req,
Expand Down Expand Up @@ -511,6 +511,11 @@ namespace {{packageName}}.Client
}
{{/supportsRetry}}

if (!response.IsSuccessStatusCode)
{
return await ToApiResponse<T>(response, default(T), req.RequestUri);
}

object responseData = deserializer.Deserialize<T>(response);

// if the response type is oneOf/anyOf, call FromJSON to deserialize the data
Expand All @@ -525,9 +530,7 @@ namespace {{packageName}}.Client

InterceptResponse(req, response);

var result = ToApiResponse<T>(response, responseData, req.RequestUri);

return result;
return await ToApiResponse<T>(response, responseData, req.RequestUri);
}

{{#supportsAsync}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public class PetApiTests : IDisposable
private PetApi instance;

private long petId = 11088;
private long notExsistentPetId = 99999;

/// <summary>
/// Create a Pet object
Expand Down Expand Up @@ -204,6 +205,25 @@ public void TestGetPetByIdAsync()
Assert.Equal("sample category name2", response.Category.Name);
}

/// <summary>
/// Test GetPetById on an not existent Id
/// </summary>
[Fact]
public void TestGetPetById_TestException()
{
PetApi petApi = new PetApi();

var exception = Assert.Throws<ApiException>(() =>
{
petApi.GetPetById(notExsistentPetId);
});

Assert.IsType<ApiException>(exception);
Assert.Equal(404, exception.ErrorCode);
Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.ErrorContent);
Assert.Equal("Error calling GetPetById: {\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", exception.Message);
}

/* a simple test for binary response. no longer in use.
[Fact]
public void TestGetByIdBinaryResponse()
Expand Down Expand Up @@ -247,7 +267,25 @@ public void TestGetPetByIdWithHttpInfoAsync()
Assert.Equal(56, response.Category.Id);
Assert.Equal("sample category name2", response.Category.Name);
}


[Fact]
public void TestGetPetByIdWithHttpInfoAsync_Test404Response()
{
PetApi petApi = new PetApi();
petApi.ExceptionFactory = null;
var response = petApi.GetPetByIdWithHttpInfoAsync(notExsistentPetId).Result;
Pet result = response.Data;

Assert.IsType<ApiResponse<Pet>>(response);
Assert.Equal(404, (int)response.StatusCode);
Assert.True(response.Headers.ContainsKey("Content-Type"));
Assert.Equal("application/json", response.Headers["Content-Type"][0]);

Assert.Null(result);
Assert.Equal("{\"code\":1,\"type\":\"error\",\"message\":\"Pet not found\"}", response.RawContent);
Assert.Equal("Not Found", response.ErrorText);
}

/// <summary>
/// Test UpdatePet
/// </summary>
Expand Down
Loading

0 comments on commit 2f2e250

Please sign in to comment.