Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#330: Handling error with complex object body #333

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/ZendeskApi.Client/Exceptions/ErrorWithMessageResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ZendeskApi.Client.Exceptions
{
/// <summary />
public class ErrorWithMessageResponse
{
/// <summary />
public ErrorWithMessageResponse()
{
}

/// <summary />
[JsonProperty("error")]
public ErrorWithMessage Error { get; internal set; }

/// <summary />
public ErrorResponse ToErrorResponse(JObject details = null) => new ErrorResponse()
{
Error = Error?.Title,
Description = Error?.Message,
Details = details
};

/// <summary />
public class ErrorWithMessage()
{
/// <summary />
[JsonProperty("message")]
public string Message { get; internal set; }

/// <summary />
[JsonProperty("title")]
public string Title { get; internal set; }
}
}
}
33 changes: 30 additions & 3 deletions src/ZendeskApi.Client/Exceptions/ZendeskRequestExceptionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,39 @@ public async Task<ZendeskRequestException> Build()
(int)_response.StatusCode <= 499 &&
!_doNotBuildErrorModelResponseCodes.Contains((int)_response.StatusCode))
{
error = await _response.Content.ReadAsAsync<ErrorResponse>();
var content = await _response.Content.ReadAsStringAsync();

try
{
error = JsonConvert.DeserializeObject<ErrorResponse>(content);
}
catch (JsonReaderException)
{
try
{
error = JsonConvert.DeserializeObject<ErrorWithMessageResponse>(content)?.ToErrorResponse();
}
catch
{
// Swallow a deserialization failure here.
}

// Throw the original exception if an error could not be deserialized.
if ( error == null )
throw;
}

if (error?.Error != null && error.Description != null)
{
var detail = Environment.NewLine + JsonConvert.SerializeObject(error.Details, Formatting.Indented);
message.AppendLine($"{error.Error}: {error.Description}. {detail}");
if (error.Details == null)
{
message.AppendLine($"{error.Error}: {error.Description.TrimEnd('.')}.");
}
else
{
var detail = Environment.NewLine + JsonConvert.SerializeObject(error.Details, Formatting.Indented);
message.AppendLine($"{error.Error}: {error.Description}. {detail}");
}
}
}

Expand Down