using System; using System.Net; using System.Net.Http; namespace Sony.Filtr.SpotifyWebAPI { [Serializable] public class SpotifyWebAPIException : Exception { public SpotifyWebAPIException() { } public SpotifyWebAPIException(string message, string method, HttpStatusCode statusCode, string reason, string requestUri, string rawResponse) : base(message) { this.StatusCode = statusCode; this.Method = method; this.Reason = reason; this.RequestUri = requestUri; this.RawResponse = rawResponse; } public SpotifyWebAPIException(string message, Exception inner) : base(message, inner) { } protected SpotifyWebAPIException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } public readonly HttpStatusCode StatusCode; public readonly string Reason; public readonly string Method; public readonly string RequestUri; public readonly string RawResponse; public static SpotifyWebAPIException FromHttpResponseMessage(HttpResponseMessage httpResponse, string userMessage = "") { if (httpResponse == null) { throw new ArgumentNullException(nameof(httpResponse)); } string method = httpResponse.RequestMessage == null ? String.Empty : httpResponse.RequestMessage.Method.ToString(); string requestUri = httpResponse.RequestMessage == null ? String.Empty : httpResponse.RequestMessage.RequestUri.ToString(); string rawResponse = httpResponse.Content.ReadAsStringAsync().Result; string message = $"User message: '{userMessage}' " + $"StatusCode: {httpResponse.StatusCode}. " + $"Reason: {httpResponse.ReasonPhrase}. " + $"Method: {method}. " + $"RequestUri: {requestUri}. " + $"Original response: {rawResponse}. "; return new SpotifyWebAPIException( message, method, httpResponse.StatusCode, httpResponse.ReasonPhrase, requestUri, rawResponse); } } }