Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add typed errors for known error types #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import (

const (
// GcmSendEndpoint is the endpoint for sending messages to the GCM server.
GcmSendEndpoint = "https://android.googleapis.com/gcm/send"
// DT: Replaced GCM endpoint with FCM. Al other references remain the same
GcmSendEndpoint = "https://fcm.googleapis.com/fcm/send"
// Initial delay before first retry, without jitter.
backoffInitialDelay = 1000
// Maximum delay before a retry.
Expand All @@ -25,6 +26,24 @@ const (
// Declared as a mutable variable for testing purposes.
var gcmSendEndpoint = GcmSendEndpoint

// Errors
type JSONParseError struct{ error }
type UnauthorizedError struct{ error }
type UnknownError struct{ error }

const (
ResponseErrorMissingRegistration = "MissingRegistration"
ResponseErrorInvalidRegistration = "InvalidRegistration"
ResponseErrorMismatchSenderID = "MismatchSenderId"
ResponseErrorNotRegistered = "NotRegistered"
ResponseErrorMessageTooBig = "MessageTooBig"
ResponseErrorInvalidDataKey = "InvalidDataKey"
ResponseErrorInvalidTTL = "InvalidTtl"
ResponseErrorUnavailable = "Unavailable"
ResponseErrorInternalServerError = "InternalServerError"
ResponseErrorInvalidPackageName = "InvalidPackageName"
)

// Sender abstracts the interaction between the application server and the
// GCM server. The developer must obtain an API key from the Google APIs
// Console page and pass it to the Sender so that it can perform authorized
Expand Down Expand Up @@ -76,8 +95,14 @@ func (s *Sender) SendNoRetry(msg *Message) (*Response, error) {
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%d error: %s", resp.StatusCode, resp.Status)
switch resp.StatusCode {
case http.StatusBadRequest:
return nil, JSONParseError{fmt.Errorf("%d error: %s", resp.StatusCode, resp.Status)}
case http.StatusUnauthorized:
return nil, UnauthorizedError{fmt.Errorf("%d error: %s", resp.StatusCode, resp.Status)}
case http.StatusOK:
default:
return nil, UnknownError{fmt.Errorf("%d error: %s", resp.StatusCode, resp.Status)}
}

body, err := ioutil.ReadAll(resp.Body)
Expand Down