Skip to content

Instantly share code, notes, and snippets.

@mstum
Created November 15, 2012 02:15
Show Gist options
  • Save mstum/4076221 to your computer and use it in GitHub Desktop.
Save mstum/4076221 to your computer and use it in GitHub Desktop.
Quick n' Dirty Web API Error Deserializer for RestSharp
// client.ClearHandlers();
// client.AddHandler("*", new WebApiJsonDeserializer());
using System;
using System.Net;
namespace RestSharp.Deserializers
{
public class WebApiJsonDeserializer : IDeserializer
{
private readonly JsonDeserializer _jsonDeserializer = new JsonDeserializer();
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public T Deserialize<T>(IRestResponse response)
{
if (response.StatusCode == HttpStatusCode.OK)
{
return _jsonDeserializer.Deserialize<T>(response);
}
var error = _jsonDeserializer.Deserialize<WebApiError>(response);
throw new WebApiException(error.Message, response.ErrorException)
{
ExceptionMessage = error.ExceptionMessage,
ExceptionType = error.ExceptionType,
MessageDetail = error.MessageDetail,
WebApiStackTrace = error.StackTrace
};
}
private class WebApiError
{
public string Message { get; set; }
public string MessageDetail { get; set; }
public string ExceptionMessage { get; set; }
public string ExceptionType { get; set; }
public string StackTrace { get; set; }
}
}
public class WebApiException : Exception
{
public string MessageDetail { get; internal set; }
public string ExceptionMessage { get; internal set; }
public string ExceptionType { get; internal set; }
public string WebApiStackTrace { get; internal set; }
public WebApiException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment