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

Handle error #11

Merged
merged 1 commit into from
Feb 15, 2019
Merged
Show file tree
Hide file tree
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
132 changes: 14 additions & 118 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,53 +7,29 @@ type ErrorType string

// List of values that ErrorType can take.
const (
ErrorTypeAPI ErrorType = "api_error"
ErrorTypeAPIConnection ErrorType = "api_connection_error"
ErrorTypeAuthentication ErrorType = "authentication_error"
ErrorTypeCard ErrorType = "card_error"
ErrorTypeInvalidRequest ErrorType = "invalid_request_error"
ErrorTypePermission ErrorType = "more_permissions_required"
ErrorTypeRateLimit ErrorType = "rate_limit_error"
)

// ErrorCode is the list of allowed values for the error's code.
type ErrorCode string

// List of values that ErrorCode can take.
const (
ErrorCodeCardDeclined ErrorCode = "card_declined"
ErrorCodeExpiredCard ErrorCode = "expired_card"
ErrorCodeIncorrectCVC ErrorCode = "incorrect_cvc"
ErrorCodeIncorrectZip ErrorCode = "incorrect_zip"
ErrorCodeIncorrectNumber ErrorCode = "incorrect_number"
ErrorCodeInvalidCVC ErrorCode = "invalid_cvc"
ErrorCodeInvalidExpiryMonth ErrorCode = "invalid_expiry_month"
ErrorCodeInvalidExpiryYear ErrorCode = "invalid_expiry_year"
ErrorCodeInvalidNumber ErrorCode = "invalid_number"
ErrorCodeInvalidSwipeData ErrorCode = "invalid_swipe_data"
ErrorCodeMissing ErrorCode = "missing"
ErrorCodeProcessingError ErrorCode = "processing_error"
ErrorCodeRateLimit ErrorCode = "rate_limit"
ErrorCodeResourceMissing ErrorCode = "resource_missing"
ErrorTypeAuthentication ErrorType = "Unauthorized"
)

// Error is the response returned when a call is unsuccessful.
// For more details see https://docs.uiza.io/#errors-code.
type Error struct {
ChargeID string `json:"charge,omitempty"`
Code ErrorCode `json:"code,omitempty"`

// Err contains an internal error with an additional level of granularity
// that can be used in some cases to get more detailed information about
// what went wrong. For example, Err may hold a CardError that indicates
// exactly what went wrong during charging a card.
Err error `json:"-"`

HTTPStatusCode int `json:"status,omitempty"`
Msg string `json:"message"`
Param string `json:"param,omitempty"`
RequestID string `json:"request_id,omitempty"`
Type ErrorType `json:"type"`
// HTTPStatusCode int `json:"status,omitempty"`
Code int `json:"code,omitempty"`
Type ErrorType `json:"type"`
// Data string `json:"data,omitempty"`
// Retryable bool `json:"retryable,omitempty"`
// Message string `json:"message,omitempty"`
// Version int `json:"version"`
// DateTime string `json:"datetime,omitempty"`
// Policy string `json:"policy,omitempty"`
// RequestID string `json:"requestId,omitempty"`
// ServiceName string `json:"serviceName,omitempty"`
DescriptionLink string
}

// Error serializes the error object to JSON and returns it as a string.
Expand All @@ -62,93 +38,13 @@ func (e *Error) Error() string {
return string(ret)
}

// APIConnectionError is a failure to connect to the uiza API.
type APIConnectionError struct {
uizaErr *Error
}

// Error serializes the error object to JSON and returns it as a string.
func (e *APIConnectionError) Error() string {
return e.uizaErr.Error()
}

// APIError is a catch all for any errors not covered by other types (and
// should be extremely uncommon).
type APIError struct {
uizaErr *Error
}

// Error serializes the error object to JSON and returns it as a string.
func (e *APIError) Error() string {
return e.uizaErr.Error()
}

// AuthenticationError is a failure to properly authenticate during a request.
type AuthenticationError struct {
uizaErr *Error
}

// Error serializes the error object to JSON and returns it as a string.
func (e *AuthenticationError) Error() string {
e.uizaErr.DescriptionLink = "https://docs.uiza.io/#authentication"
return e.uizaErr.Error()
}

// PermissionError results when you attempt to make an API request
// for which your API key doesn't have the right permissions.
type PermissionError struct {
uizaErr *Error
}

// Error serializes the error object to JSON and returns it as a string.
func (e *PermissionError) Error() string {
return e.uizaErr.Error()
}

// CardError are the most common type of error you should expect to handle.
// They result when the user enters a card that can't be charged for some
// reason.
type CardError struct {
uizaErr *Error
DeclineCode string `json:"decline_code,omitempty"`
}

// Error serializes the error object to JSON and returns it as a string.
func (e *CardError) Error() string {
return e.uizaErr.Error()
}

// InvalidRequestError is an error that occurs when a request contains invalid
// parameters.
type InvalidRequestError struct {
uizaErr *Error
}

// Error serializes the error object to JSON and returns it as a string.
func (e *InvalidRequestError) Error() string {
return e.uizaErr.Error()
}

// RateLimitError occurs when the uiza API is hit to with too many requests
// too quickly and indicates that the current request has been rate limited.
type RateLimitError struct {
uizaErr *Error
}

// Error serializes the error object to JSON and returns it as a string.
func (e *RateLimitError) Error() string {
return e.uizaErr.Error()
}

// rawError deserializes the outer JSON object returned in an error response
// from the API.
type rawError struct {
E *rawErrorInternal `json:"error,omitempty"`
}

// rawErrorInternal embeds Error to deserialize all the standard error fields,
// but also adds other fields that may or may not be present depending on error
// type to help with deserialization. (e.g. Declinecode).
type rawErrorInternal struct {
*Error
DeclineCode *string `json:"decline_code,omitempty"`
}
44 changes: 14 additions & 30 deletions uiza.go
Original file line number Diff line number Diff line change
Expand Up @@ -414,10 +414,9 @@ func (s *BackendImplementation) Do(req *http.Request, body *bytes.Buffer, v *str
return err
}

//TODO: handle error
// if res.StatusCode >= 400 {
// return s.ResponseToError(res, resBody)
// }
if res.StatusCode >= 400 {
return s.ResponseToError(res, resBody)
}

if s.LogLevel > 2 {
s.Logger.Printf("Response: %s\n", string(resBody))
Expand All @@ -433,48 +432,33 @@ func (s *BackendImplementation) Do(req *http.Request, body *bytes.Buffer, v *str

// ResponseToError converts a uiza response to an Error.
func (s *BackendImplementation) ResponseToError(res *http.Response, resBody []byte) error {
var raw rawError
var raw Error
if err := json.Unmarshal(resBody, &raw); err != nil {
return err
}

// no error in resBody
if raw.E == nil {
if &raw == nil {
err := errors.New(string(resBody))
if s.LogLevel > 0 {
s.Logger.Printf("Unparsable error returned from Uiza: %v\n", err)
}
return err
}
raw.E.HTTPStatusCode = res.StatusCode
raw.E.RequestID = res.Header.Get("Request-Id")

// raw.HTTPStatusCode = res.StatusCode
// raw.RequestID = res.Header.Get("Request-Id")

var typedError error
switch raw.E.Type {
case ErrorTypeAPI:
typedError = &APIError{uizaErr: raw.E.Error}
case ErrorTypeAPIConnection:
typedError = &APIConnectionError{uizaErr: raw.E.Error}
switch raw.Type {
case ErrorTypeAuthentication:
typedError = &AuthenticationError{uizaErr: raw.E.Error}
case ErrorTypeCard:
cardErr := &CardError{uizaErr: raw.E.Error}
if raw.E.DeclineCode != nil {
cardErr.DeclineCode = *raw.E.DeclineCode
}
typedError = cardErr
case ErrorTypeInvalidRequest:
typedError = &InvalidRequestError{uizaErr: raw.E.Error}
case ErrorTypePermission:
typedError = &PermissionError{uizaErr: raw.E.Error}
case ErrorTypeRateLimit:
typedError = &RateLimitError{uizaErr: raw.E.Error}
typedError = &AuthenticationError{uizaErr: &raw}
}
raw.E.Err = typedError

raw.Err = typedError
if s.LogLevel > 0 {
s.Logger.Printf("Error encountered from Uiza: %v\n", raw.E.Error)
s.Logger.Printf("Error encountered from Uiza: %v\n", raw)
}
return raw.E.Error
return &raw
}

// SetMaxNetworkRetries sets max number of retries on failed requests
Expand Down