2020-05-01 19:05:28 +01:00
|
|
|
using Newtonsoft.Json;
|
|
|
|
using Newtonsoft.Json.Linq;
|
|
|
|
using SpotifyAPI.Web.Http;
|
2020-05-05 14:30:00 +01:00
|
|
|
using System;
|
|
|
|
using System.Runtime.Serialization;
|
2020-05-01 19:05:28 +01:00
|
|
|
|
|
|
|
namespace SpotifyAPI.Web
|
|
|
|
{
|
2020-05-05 14:30:00 +01:00
|
|
|
[Serializable]
|
2020-05-25 17:00:38 +01:00
|
|
|
public class APIException : Exception
|
2020-05-01 19:05:28 +01:00
|
|
|
{
|
2020-05-25 17:00:38 +01:00
|
|
|
public IResponse? Response { get; set; }
|
2020-05-05 14:30:00 +01:00
|
|
|
|
2020-05-01 19:05:28 +01:00
|
|
|
public APIException(IResponse response) : base(ParseAPIErrorMessage(response))
|
|
|
|
{
|
|
|
|
Ensure.ArgumentNotNull(response, nameof(response));
|
|
|
|
|
|
|
|
Response = response;
|
|
|
|
}
|
|
|
|
|
2020-05-05 14:30:00 +01:00
|
|
|
public APIException()
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
public APIException(string message) : base(message)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2020-05-25 17:00:38 +01:00
|
|
|
public APIException(string message, Exception innerException) : base(message, innerException)
|
2020-05-05 14:30:00 +01:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
protected APIException(SerializationInfo info, StreamingContext context) : base(info, context)
|
|
|
|
{
|
|
|
|
Response = info.GetValue("APIException.Response", typeof(IResponse)) as IResponse;
|
|
|
|
}
|
|
|
|
|
2020-05-25 17:00:38 +01:00
|
|
|
private static string? ParseAPIErrorMessage(IResponse response)
|
2020-05-01 19:05:28 +01:00
|
|
|
{
|
|
|
|
var body = response.Body as string;
|
|
|
|
if (string.IsNullOrEmpty(body))
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
try
|
|
|
|
{
|
2020-05-25 17:00:38 +01:00
|
|
|
JObject bodyObject = JObject.Parse(body!);
|
2020-05-01 19:05:28 +01:00
|
|
|
JObject error = bodyObject.Value<JObject>("error");
|
|
|
|
if (error != null)
|
|
|
|
{
|
|
|
|
return error.Value<string>("message");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
catch (JsonReaderException)
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2020-05-05 14:30:00 +01:00
|
|
|
public override void GetObjectData(SerializationInfo info, StreamingContext context)
|
|
|
|
{
|
|
|
|
base.GetObjectData(info, context);
|
|
|
|
info.AddValue("APIException.Response", Response);
|
|
|
|
}
|
2020-05-01 19:05:28 +01:00
|
|
|
}
|
|
|
|
}
|