Skip to content

Commit

Permalink
Changing exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
slorello89 committed Jan 31, 2020
1 parent dae26d6 commit d0568fb
Show file tree
Hide file tree
Showing 10 changed files with 113 additions and 187 deletions.
6 changes: 1 addition & 5 deletions Nexmo.Api/Account.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,11 +177,7 @@ public static Settings SetSettings(string newsecret = null, string httpMoCallbac
if (null != httpDrCallbackurlCom)
parameters.Add("drCallBackUrl", httpDrCallbackurlCom);

var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(Account), "/account/settings"), parameters, credentials);

// TODO: update secret in config?

return JsonConvert.DeserializeObject<Settings>(response.JsonResponse);
return ApiRequest.DoPostRequest<Settings>(ApiRequest.GetBaseUriFor(typeof(Account), "/account/settings"), parameters, credentials);
}

/// <summary>
Expand Down
8 changes: 2 additions & 6 deletions Nexmo.Api/Application.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,7 @@ public class Application
/// <returns></returns>
public static ApplicationResponse Create(ApplicationRequest request, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(Application), "/v1/applications"), request, creds);

return JsonConvert.DeserializeObject<ApplicationResponse>(response.JsonResponse);
return ApiRequest.DoPostRequest<ApplicationResponse>(ApiRequest.GetBaseUriFor(typeof(Application), "/v1/applications"), request, creds);
}

/// <summary>
Expand Down Expand Up @@ -158,10 +156,8 @@ public static List<ApplicationResponse> List(int PageSize = 10, int PageIndex =
public static ApplicationResponse Update(ApplicationRequest request, Credentials creds = null)
{
var sb = ApiRequest.GetQueryStringBuilderFor(request);
var response = ApiRequest.DoPutRequest(ApiRequest.GetBaseUriFor(typeof(Application),
return ApiRequest.DoPutRequest<ApplicationResponse>(ApiRequest.GetBaseUriFor(typeof(Application),
$"/v1/applications/{request.id}?{sb}"), null, creds);

return JsonConvert.DeserializeObject<ApplicationResponse>(response.JsonResponse);
}

/// <summary>
Expand Down
10 changes: 0 additions & 10 deletions Nexmo.Api/Client/NumberInsight.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,5 @@ public Api.NumberInsight.NumberInsightAsyncRequestResponse RequestAsync(Api.Numb
{
return Api.NumberInsight.RequestAsync(request, creds ?? Credentials);
}

/// <summary>
/// Deserializes a NumberInsight response JSON string
/// </summary>
/// <param name="json">NumberInsight response JSON string</param>
/// <returns></returns>
public Api.NumberInsight.NumberInsightAdvancedResponse Response(string json)
{
return Api.NumberInsight.Response(json);
}
}
}
5 changes: 4 additions & 1 deletion Nexmo.Api/Conversion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,18 @@ public class ConversionRequest
[JsonProperty("timestamp")]
public DateTime Timestamp { get; set; }
}
public class ConversionResult
{

}
/// <summary>
/// Tells if a message or call was successful.
/// </summary>
/// <param name="request"></param>
/// <param name="creds"></param>
public static void SubmitConversion (ConversionRequest request, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(new Uri($"https://api.nexmo.com/conversions/{ConversionType}"), request, creds);
ApiRequest.DoPostRequest<ConversionResult>(new Uri($"https://api.nexmo.com/conversions/{ConversionType}"), request, creds);
}
}
}
12 changes: 3 additions & 9 deletions Nexmo.Api/Number.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,14 +123,12 @@ public static SearchResults Search(SearchRequest request, Credentials creds = nu
/// <returns></returns>
public static ResponseBase Buy(string country, string number, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(Number), "/number/buy"), new Dictionary<string, string>
return ApiRequest.DoPostRequest<ResponseBase>(ApiRequest.GetBaseUriFor(typeof(Number), "/number/buy"), new Dictionary<string, string>
{
{"country", country},
{"msisdn", number}
},
creds);

return JsonConvert.DeserializeObject<ResponseBase>(response.JsonResponse);
}

/// <summary>
Expand All @@ -141,9 +139,7 @@ public static ResponseBase Buy(string country, string number, Credentials creds
/// <returns></returns>
public static ResponseBase Update(NumberUpdateCommand cmd, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(Number), "/number/update"), cmd, creds);

return JsonConvert.DeserializeObject<ResponseBase>(response.JsonResponse);
return ApiRequest.DoPostRequest<ResponseBase>(ApiRequest.GetBaseUriFor(typeof(Number), "/number/update"), cmd, creds);
}

/// <summary>
Expand All @@ -155,14 +151,12 @@ public static ResponseBase Update(NumberUpdateCommand cmd, Credentials creds = n
/// <returns></returns>
public static ResponseBase Cancel(string country, string number, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(Number), "/number/cancel"), new Dictionary<string, string>
return ApiRequest.DoPostRequest<ResponseBase>(ApiRequest.GetBaseUriFor(typeof(Number), "/number/cancel"), new Dictionary<string, string>
{
{"country", country},
{"msisdn", number}
},
creds);

return JsonConvert.DeserializeObject<ResponseBase>(response.JsonResponse);
}
}
}
37 changes: 19 additions & 18 deletions Nexmo.Api/NumberInsight.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ namespace Nexmo.Api
{
public static class NumberInsight
{
private const string BASIC = "basic";
private const string STANDARD = "standard";
private const string ADVANCED = "advanced";
public class NumberInsightRequest
{
/// <summary>
Expand Down Expand Up @@ -236,9 +239,7 @@ public class NumberInsightAsyncRequestResponse
/// <returns></returns>
public static NumberInsightBasicResponse RequestBasic(NumberInsightRequest request, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(NumberVerify), "/ni/basic/json"), request, creds);

return JsonConvert.DeserializeObject<NumberInsightBasicResponse>(response.JsonResponse);
return SendSynchronousInsightRequest<NumberInsightBasicResponse>(request, BASIC, creds);
}

/// <summary>
Expand All @@ -249,22 +250,29 @@ public static NumberInsightBasicResponse RequestBasic(NumberInsightRequest reque
/// <returns></returns>
public static NumberInsightStandardResponse RequestStandard(NumberInsightRequest request, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(NumberVerify), "/ni/standard/json"), request, creds);

return JsonConvert.DeserializeObject<NumberInsightStandardResponse>(response.JsonResponse);
return SendSynchronousInsightRequest<NumberInsightStandardResponse>(request, STANDARD, creds);
}

/// <summary>
/// Retrieve validity, roaming, and reachability information about a mobile phone number.
/// </summary>
/// <param name="request">NI advenced request</param>
/// <param name="creds">(Optional) Overridden credentials for only this request</param>
/// <exception cref="NumberInishghtRequestException">Thrown when response holds a bad status</exception>
/// <returns></returns>
public static NumberInsightAdvancedResponse RequestAdvanced(NumberInsightRequest request, Credentials creds = null)
{
var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(NumberVerify), "/ni/advanced/json"), request, creds);
return SendSynchronousInsightRequest<NumberInsightAdvancedResponse>(request, ADVANCED, creds);
}

return JsonConvert.DeserializeObject<NumberInsightAdvancedResponse>(response.JsonResponse);
public static T SendSynchronousInsightRequest<T>(NumberInsightRequest request, string level, Credentials creds = null) where T : NumberInsightBasicResponse
{
var response = ApiRequest.DoPostRequest<T>(ApiRequest.GetBaseUriFor(typeof(NumberVerify), $"/ni/{level}/json"), request, creds);
if (response?.Status != "0")
{
throw new NumberInsightRequestException($"Number Inisght Request failed with status of: {response?.Status} and with an error message of {response?.StatusMessage}");
}
return response;
}

/// <summary>
Expand Down Expand Up @@ -294,19 +302,12 @@ public static NumberInsightAsyncRequestResponse RequestAsync(NumberInsightAsyncR
parameters.Add("ip", request.IPAddress);
}

var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(NumberVerify), "/ni/advanced/async/json"), parameters, creds);

return JsonConvert.DeserializeObject<NumberInsightAsyncRequestResponse>(response.JsonResponse);
return ApiRequest.DoPostRequest<NumberInsightAsyncRequestResponse>(ApiRequest.GetBaseUriFor(typeof(NumberVerify), "/ni/advanced/async/json"), parameters, creds);
}

/// <summary>
/// Deserializes a NumberInsight response JSON string
/// </summary>
/// <param name="json">NumberInsight response JSON string</param>
/// <returns></returns>
public static NumberInsightAdvancedResponse Response(string json)
public class NumberInsightRequestException : Exception
{
return JsonConvert.DeserializeObject<NumberInsightAdvancedResponse>(json);
public NumberInsightRequestException(string message) : base(message) { }
}
}
}
147 changes: 37 additions & 110 deletions Nexmo.Api/Request/ApiRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Nexmo.Api.Request
{
Expand Down Expand Up @@ -163,35 +164,8 @@ internal static string DoRequest(Uri uri, Credentials creds)
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authBytes));
}

using (LogProvider.OpenMappedContext("ApiRequest.DoRequest",uri.GetHashCode()))
{
Logger.Debug($"GET {uri}");
var sendTask = Configuration.Instance.Client.SendAsync(req);
sendTask.Wait();

if (!sendTask.Result.IsSuccessStatusCode)
{
Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
"true", StringComparison.OrdinalIgnoreCase) == 0)
{
sendTask.Result.EnsureSuccessStatusCode();
}
}

var readTask = sendTask.Result.Content.ReadAsStreamAsync();
readTask.Wait();

string json;
using (var sr = new StreamReader(readTask.Result))
{
json = sr.ReadToEnd();
}
Logger.Debug(json);
return json;
}
Logger.Debug($"GET {uri}");
return SendRequest(req).JsonResponse;
}

/// <summary>
Expand Down Expand Up @@ -222,50 +196,14 @@ public static NexmoResponse DoRequest(string method, Uri uri, Dictionary<string,
var data = Encoding.ASCII.GetBytes(sb.ToString());
req.Content = new ByteArrayContent(data);
req.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

using (LogProvider.OpenMappedContext("ApiRequest.DoRequest",uri.GetHashCode()))
{
Logger.Debug($"{method} {uri} {sb}");
var sendTask = Configuration.Instance.Client.SendAsync(req);
sendTask.Wait();

if (!sendTask.Result.IsSuccessStatusCode)
{
Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
"true", StringComparison.OrdinalIgnoreCase) == 0)
{
sendTask.Result.EnsureSuccessStatusCode();
}

return new NexmoResponse
{
Status = sendTask.Result.StatusCode
};
}

string json;
var readTask = sendTask.Result.Content.ReadAsStreamAsync();
readTask.Wait();
using (var sr = new StreamReader(readTask.Result))
{
json = sr.ReadToEnd();
}
Logger.Debug(json);
return new NexmoResponse
{
Status = sendTask.Result.StatusCode,
JsonResponse = json
};
}
Logger.Debug($"{method} {uri} {sb}");
return SendRequest(req);
}

public static NexmoResponse DoRequest(string method, Uri uri, object requestBody, Credentials creds = null)
{
var sb = new StringBuilder();
var parameters = new Dictionary<string, string>();
sb = BuildQueryString(parameters, creds);
var sb = BuildQueryString(parameters, creds);

var requestContent = JsonConvert.SerializeObject(requestBody);

Expand All @@ -276,46 +214,34 @@ public static NexmoResponse DoRequest(string method, Uri uri, object requestBody
Content = new StringContent(requestContent, Encoding.UTF8, "application/json"),
};
VersionedApiRequest.SetUserAgent(ref req, creds);

using (LogProvider.OpenMappedContext("ApiRequest.DoRequest", uri.GetHashCode()))
Logger.Debug($"{method} {uri} {sb}");
return SendRequest(req);
}
public static NexmoResponse SendRequest(HttpRequestMessage req)
{
var response = Configuration.Instance.Client.SendAsync(req).Result;
var stream = response.Content.ReadAsStreamAsync().Result;
string json;
using (var sr = new StreamReader(stream))
{
Logger.Debug($"{method} {uri} {sb}");
var sendTask = Configuration.Instance.Client.SendAsync(req);
sendTask.Wait();

if (!sendTask.Result.IsSuccessStatusCode)
{

Logger.Error($"FAIL: {sendTask.Result.StatusCode}");

if (string.Compare(Configuration.Instance.Settings["appSettings:Nexmo.Api.EnsureSuccessStatusCode"],
"true", StringComparison.OrdinalIgnoreCase) == 0)
{
sendTask.Result.EnsureSuccessStatusCode();
}

return new NexmoResponse
{
Status = sendTask.Result.StatusCode
};
}

string jsonResult;
var readTask = sendTask.Result.Content.ReadAsStreamAsync();
readTask.Wait();
using (var sr = new StreamReader(readTask.Result))
{
jsonResult = sr.ReadToEnd();
}
Logger.Debug(jsonResult);
json = sr.ReadToEnd();
}
try
{
Logger.Debug(json);
response.EnsureSuccessStatusCode();
return new NexmoResponse
{
Status = sendTask.Result.StatusCode,
JsonResponse = jsonResult
Status = response.StatusCode,
JsonResponse = json
};
}
catch (HttpRequestException exception)
{
Logger.Error($"FAIL: {response.StatusCode}");
throw new NexmoHttpRequestException(exception.Message) { StatusCode = response.StatusCode, Json = json };
}
}

internal static HttpResponseMessage DoRequestJwt(Uri uri, Credentials creds)
{
var appId = creds?.ApplicationId ?? Configuration.Instance.Settings["appSettings:Nexmo.Application.Id"];
Expand Down Expand Up @@ -352,20 +278,21 @@ internal static HttpResponseMessage DoRequestJwt(Uri uri, Credentials creds)
}
}

internal static NexmoResponse DoPostRequest(Uri uri, object parameters, Credentials creds = null)
internal static T DoPostRequest<T>(Uri uri, object parameters, Credentials creds = null)
{
var apiParams = GetParameters(parameters);
return DoPostRequest(uri, apiParams, creds);
return DoPostRequest<T>(uri, apiParams, creds);
}

internal static NexmoResponse DoPostRequestWithContent(Uri uri, object parameters, Credentials creds = null)
internal static T DoPostRequest<T>(Uri uri, Dictionary<string, string> parameters, Credentials creds = null)
{
return DoRequestWithContent(uri, parameters, creds);
var response = DoRequest("POST", uri, parameters, creds);
return JsonConvert.DeserializeObject<T>(response.JsonResponse);
}
internal static T DoPutRequest<T>(Uri uri, Dictionary<string, string> parameters, Credentials creds = null) {
var response = DoRequest("PUT", uri, parameters, creds);
return JsonConvert.DeserializeObject<T>(response.JsonResponse);
}

internal static NexmoResponse DoPostRequest(Uri uri, Dictionary<string, string> parameters, Credentials creds = null) => DoRequest("POST", uri, parameters, creds);
internal static NexmoResponse DoRequestWithContent(Uri uri, object parameters, Credentials creds = null) => DoRequest("POST", uri, parameters, creds);
internal static NexmoResponse DoPutRequest(Uri uri, Dictionary<string, string> parameters, Credentials creds = null) => DoRequest("PUT", uri, parameters, creds);
internal static NexmoResponse DoDeleteRequest(Uri uri, Dictionary<string, string> parameters, Credentials creds = null) => DoRequest("DELETE", uri, parameters, creds);
}
}
Loading

0 comments on commit d0568fb

Please sign in to comment.