Skip to content

Commit

Permalink
Improved Exception inheritance chain and consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
Redth committed Mar 16, 2016
1 parent dffd6d9 commit 8af0cc5
Show file tree
Hide file tree
Showing 15 changed files with 76 additions and 35 deletions.
2 changes: 1 addition & 1 deletion PushSharp.Amazon/AdmConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public async Task Send (AdmNotification notification)
case HttpStatusCode.BadGateway: //400
case HttpStatusCode.BadRequest: //
if ("InvalidRegistrationId".Equals (reason, StringComparison.InvariantCultureIgnoreCase)) {
throw new DeviceSubscriptonExpiredException {
throw new DeviceSubscriptonExpiredException (notification) {
OldSubscriptionId = regId,
ExpiredAt = DateTime.UtcNow
};
Expand Down
10 changes: 7 additions & 3 deletions PushSharp.Amazon/Exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,25 @@ namespace PushSharp.Amazon
{
public class AdmRateLimitExceededException : NotificationException
{
public AdmRateLimitExceededException (string reason, INotification notification)
public AdmRateLimitExceededException (string reason, AdmNotification notification)
: base ("Rate Limit Exceeded (" + reason + ")", notification)
{
Notification = notification;
Reason = reason;
}

public new AdmNotification Notification { get; set; }
public string Reason { get; private set; }
}

public class AdmMessageTooLargeException : NotificationException
{
public AdmMessageTooLargeException (INotification notification)
public AdmMessageTooLargeException (AdmNotification notification)
: base ("ADM Message too Large, must be <= 6kb", notification)
{
Notification = notification;
}

public new AdmNotification Notification { get; set; }
}
}

10 changes: 5 additions & 5 deletions PushSharp.Apple/ApnsConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,19 +108,19 @@ void CheckIsApnsCertificate ()
var commonName = Certificate.SubjectName.Name;

if (!issuerName.Contains ("Apple"))
throw new ApnsConnectionException ("Your Certificate does not appear to be issued by Apple! Please check to ensure you have the correct certificate!");
throw new ArgumentOutOfRangeException ("Your Certificate does not appear to be issued by Apple! Please check to ensure you have the correct certificate!");

if (!Regex.IsMatch (commonName, "Apple.*?Push Services")
&& !commonName.Contains ("Website Push ID:"))
throw new ApnsConnectionException ("Your Certificate is not a valid certificate for connecting to Apple's APNS servers");
throw new ArgumentOutOfRangeException ("Your Certificate is not a valid certificate for connecting to Apple's APNS servers");

if (commonName.Contains ("Development") && ServerEnvironment != ApnsServerEnvironment.Sandbox)
throw new ApnsConnectionException ("You are using a certificate created for connecting only to the Sandbox APNS server but have selected a different server environment to connect to.");
throw new ArgumentOutOfRangeException ("You are using a certificate created for connecting only to the Sandbox APNS server but have selected a different server environment to connect to.");

if (commonName.Contains ("Production") && ServerEnvironment != ApnsServerEnvironment.Production)
throw new ApnsConnectionException ("You are using a certificate created for connecting only to the Production APNS server but have selected a different server environment to connect to.");
throw new ArgumentOutOfRangeException ("You are using a certificate created for connecting only to the Production APNS server but have selected a different server environment to connect to.");
} else {
throw new ApnsConnectionException ("You must provide a Certificate to connect to APNS with!");
throw new ArgumentOutOfRangeException ("You must provide a Certificate to connect to APNS with!");
}
}

Expand Down
2 changes: 1 addition & 1 deletion PushSharp.Apple/ApnsConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ async Task SendBatch ()
} catch (Exception ex) {
Log.Error ("APNS-CLIENT[{0}]: Send Batch Error: Batch ID={1}, Error={2}", id, batchId, ex);
foreach (var n in toSend)
n.CompleteFailed (ex);
n.CompleteFailed (new ApnsNotificationException (ApnsNotificationErrorStatusCode.ConnectionError, n.Notification, ex));
}

Log.Info ("APNS-Client[{0}]: Sent Batch, waiting for possible response...", id);
Expand Down
14 changes: 11 additions & 3 deletions PushSharp.Apple/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using PushSharp.Core;

namespace PushSharp.Apple
{
Expand All @@ -14,24 +15,31 @@ public enum ApnsNotificationErrorStatusCode
InvalidPayloadSize = 7,
InvalidToken = 8,
Shutdown = 10,
ConnectionError = 254,
Unknown = 255
}

public class ApnsNotificationException : Exception
public class ApnsNotificationException : NotificationException
{
public ApnsNotificationException(byte errorStatusCode, ApnsNotification notification)
: this(ToErrorStatusCode(errorStatusCode), notification)
{ }

public ApnsNotificationException (ApnsNotificationErrorStatusCode errorStatusCode, ApnsNotification notification)
: base ("Apns notification error: '" + errorStatusCode + "'")
: base ("Apns notification error: '" + errorStatusCode + "'", notification)
{
Notification = notification;
ErrorStatusCode = errorStatusCode;
}

public ApnsNotification Notification { get; set; }
public ApnsNotificationException (ApnsNotificationErrorStatusCode errorStatusCode, ApnsNotification notification, Exception innerException)
: base ("Apns notification error: '" + errorStatusCode + "'", notification, innerException)
{
Notification = notification;
ErrorStatusCode = errorStatusCode;
}

public new ApnsNotification Notification { get; set; }
public ApnsNotificationErrorStatusCode ErrorStatusCode { get; private set; }

private static ApnsNotificationErrorStatusCode ToErrorStatusCode(byte errorStatusCode)
Expand Down
2 changes: 1 addition & 1 deletion PushSharp.Blackberry/BlackberryConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public async Task Send (BlackberryNotification notification)
status.NotificationStatus = notStatus;

if (status.NotificationStatus == BlackberryNotificationStatus.NoAppReceivePush)
throw new DeviceSubscriptonExpiredException ();
throw new DeviceSubscriptonExpiredException (notification);

if (status.HttpStatus == HttpStatusCode.OK
&& status.NotificationStatus == BlackberryNotificationStatus.RequestAcceptedForProcessing)
Expand Down
3 changes: 3 additions & 0 deletions PushSharp.Blackberry/Exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ public class BlackberryNotificationException : NotificationException
public BlackberryNotificationException (BlackberryMessageStatus msgStatus, string desc, BlackberryNotification notification)
:base (desc + " - " + msgStatus, notification)
{
Notification = notification;
MessageStatus = msgStatus;
}

public new BlackberryNotification Notification { get; set; }

public BlackberryMessageStatus MessageStatus { get; private set; }
}
}
Expand Down
9 changes: 5 additions & 4 deletions PushSharp.Core/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using System;
using System.Collections.Generic;

namespace PushSharp.Core
{
public class DeviceSubscriptonExpiredException : Exception
public class DeviceSubscriptonExpiredException : NotificationException
{
public DeviceSubscriptonExpiredException () : base ("Device Subscription has Expired")
public DeviceSubscriptonExpiredException (INotification notification) : base ("Device Subscription has Expired", notification)
{
ExpiredAt = DateTime.UtcNow;
}
Expand All @@ -30,9 +31,9 @@ public NotificationException (string message, INotification notification, Except
public INotification Notification { get; set; }
}

public class RetryAfterException : Exception
public class RetryAfterException : NotificationException
{
public RetryAfterException (string message, DateTime retryAfterUtc) : base (message)
public RetryAfterException (INotification notification, string message, DateTime retryAfterUtc) : base (message, notification)
{
RetryAfterUtc = retryAfterUtc;
}
Expand Down
16 changes: 16 additions & 0 deletions PushSharp.Firefox/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using PushSharp.Core;

namespace PushSharp.Firefox
{
public class FirefoxNotificationException : NotificationException
{
public FirefoxNotificationException (FirefoxNotification notification, string msg)
: base (msg, notification)
{
Notification = notification;
}

public new FirefoxNotification Notification { get; private set; }
}
}
2 changes: 1 addition & 1 deletion PushSharp.Firefox/FirefoxConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public async Task Send (FirefoxNotification notification)
var result = await http.PutAsync (notification.EndPointUrl, new StringContent (data));

if (result.StatusCode != HttpStatusCode.OK && result.StatusCode != HttpStatusCode.NoContent) {
throw new NotificationException ("Notification Failed", notification);
throw new FirefoxNotificationException (notification, "HTTP Status: " + result.StatusCode);
}
}
}
Expand Down
1 change: 1 addition & 0 deletions PushSharp.Firefox/PushSharp.Firefox.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
<Compile Include="FirefoxNotification.cs" />
<Compile Include="FirefoxConnection.cs" />
<Compile Include="FirefoxConfiguration.cs" />
<Compile Include="Exceptions.cs" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
Expand Down
10 changes: 7 additions & 3 deletions PushSharp.Google/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
using System;
using System.Collections.Generic;
using PushSharp.Core;

namespace PushSharp.Google
{
public class GcmConnectionException : Exception
public class GcmNotificationException : NotificationException
{
public GcmConnectionException (string msg) : base (msg)
public GcmNotificationException (GcmNotification notification, string msg) : base (msg, notification)
{
Notification = notification;
}

public GcmConnectionException (string msg, string description) : base (msg)
public GcmNotificationException (GcmNotification notification, string msg, string description) : base (msg, notification)
{
Notification = notification;
Description = description;
}

public new GcmNotification Notification { get; private set; }
public string Description { get; private set; }
}

Expand Down
23 changes: 13 additions & 10 deletions PushSharp.Google/GcmServiceConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,13 @@ async Task processResponseOk (HttpResponseMessage httpResponse, GcmNotification
oldRegistrationId = singleResultNotification.To;
}

multicastResult.Failed.Add (singleResultNotification, new DeviceSubscriptonExpiredException {
OldSubscriptionId = oldRegistrationId,
NewSubscriptionId = newRegistrationId
});
multicastResult.Failed.Add (singleResultNotification,
new DeviceSubscriptonExpiredException (singleResultNotification) {
OldSubscriptionId = oldRegistrationId,
NewSubscriptionId = newRegistrationId
});
} else if (r.ResponseStatus == GcmResponseStatus.Unavailable) { // Unavailable
multicastResult.Failed.Add (singleResultNotification, new GcmConnectionException ("Unavailable Response Status"));
multicastResult.Failed.Add (singleResultNotification, new GcmNotificationException (singleResultNotification, "Unavailable Response Status"));
} else if (r.ResponseStatus == GcmResponseStatus.NotRegistered) { //Bad registration Id
var oldRegistrationId = string.Empty;

Expand All @@ -144,9 +145,11 @@ async Task processResponseOk (HttpResponseMessage httpResponse, GcmNotification
oldRegistrationId = singleResultNotification.To;
}

multicastResult.Failed.Add (singleResultNotification, new DeviceSubscriptonExpiredException { OldSubscriptionId = oldRegistrationId });
multicastResult.Failed.Add (singleResultNotification,
new DeviceSubscriptonExpiredException (singleResultNotification) {
OldSubscriptionId = oldRegistrationId });
} else {
multicastResult.Failed.Add (singleResultNotification, new GcmConnectionException ("Unknown Failure: " + r.ResponseStatus));
multicastResult.Failed.Add (singleResultNotification, new GcmNotificationException (singleResultNotification, "Unknown Failure: " + r.ResponseStatus));
}

index++;
Expand Down Expand Up @@ -180,19 +183,19 @@ async Task processResponseError (HttpResponseMessage httpResponse, GcmNotificati
throw new UnauthorizedAccessException ("GCM Authorization Failed");

if (httpResponse.StatusCode == HttpStatusCode.BadRequest)
throw new GcmConnectionException ("HTTP 400 Bad Request", responseBody);
throw new GcmNotificationException (notification, "HTTP 400 Bad Request", responseBody);

if ((int)httpResponse.StatusCode >= 500 && (int)httpResponse.StatusCode < 600) {
//First try grabbing the retry-after header and parsing it.
var retryAfterHeader = httpResponse.Headers.RetryAfter;

if (retryAfterHeader != null && retryAfterHeader.Delta.HasValue) {
var retryAfter = retryAfterHeader.Delta.Value;
throw new RetryAfterException ("GCM Requested Backoff", DateTime.UtcNow + retryAfter);
throw new RetryAfterException (notification, "GCM Requested Backoff", DateTime.UtcNow + retryAfter);
}
}

throw new GcmConnectionException ("GCM HTTP Error: " + httpResponse.StatusCode, responseBody);
throw new GcmNotificationException (notification, "GCM HTTP Error: " + httpResponse.StatusCode, responseBody);
}

static GcmResponseStatus GetGcmResponseStatus (string str)
Expand Down
3 changes: 2 additions & 1 deletion PushSharp.Windows/Exceptions.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
using System;
using PushSharp.Core;

namespace PushSharp.Windows
{
public class WnsNotificationException : PushSharp.Core.NotificationException
public class WnsNotificationException : NotificationException
{
public WnsNotificationException (WnsNotificationStatus status) : base (status.ErrorDescription, status.Notification)
{
Expand Down
4 changes: 2 additions & 2 deletions PushSharp.Windows/WnsConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,12 +134,12 @@ public async Task Send (WnsNotification notification)
//401
if (status.HttpStatus == HttpStatusCode.Unauthorized) {
AccessTokenManager.InvalidateAccessToken (accessToken);
throw new RetryAfterException ("Access token expired", DateTime.UtcNow.AddSeconds (5));
throw new RetryAfterException (notification, "Access token expired", DateTime.UtcNow.AddSeconds (5));
}

//404 or 410
if (status.HttpStatus == HttpStatusCode.NotFound || status.HttpStatus == HttpStatusCode.Gone) {
throw new DeviceSubscriptonExpiredException {
throw new DeviceSubscriptonExpiredException (notification) {
OldSubscriptionId = notification.ChannelUri,
ExpiredAt = DateTime.UtcNow
};
Expand Down

4 comments on commit 8af0cc5

@akousmata
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When will this commit be available in nuget? I just got the latest version via nuget and am missing the GcmNotificationException reference which was just added in this commit. In your Read.me, you are referencing this class, so retrieving the latest build from nuget and using the example from the Read.me, the code doesn't compile.

@Redth
Copy link
Owner Author

@Redth Redth commented on 8af0cc5 Mar 21, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's on Nuget now, v4.0.x

@akousmata
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Haha, just saw it when I got your message.

@akousmata
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's weird, though, when I installed it this morning it was 3.0, and just now I saw the 4.0 after I went back. So I assumed I had the latest on 3.0. Thanks for the heads up.

Please sign in to comment.