-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patherrors.go
More file actions
84 lines (71 loc) · 1.62 KB
/
errors.go
File metadata and controls
84 lines (71 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package chargehound
import (
"encoding/json"
"net/http"
)
type ErrorType string
const (
BadRequestError = ErrorType("Bad Request")
UnauthorizedError = ErrorType("Unauthorized")
ForbiddenError = ErrorType("Forbidden")
NotFoundError = ErrorType("Not Found")
InternalServerError = ErrorType("Server Error")
GenericError = ErrorType("Error")
)
// A Chargehound API error
type Error interface {
// The error message
Error() string
// The HTTP status code
StatusCode() int
// The Go exception type
Type() ErrorType
// The error type string from the API
ApiErrorType() string
}
type errorResponse struct {
Status int
ErrorType ErrorType
Message string
ApiType string `json:"type"`
}
type errorJSON struct {
Url string
Livemode bool
Error errorResponse
}
func responseToError(res *http.Response) error {
var errRes errorJSON
decoder := json.NewDecoder(res.Body)
err := decoder.Decode(&errRes)
if err != nil {
return err
}
switch errRes.Error.Status {
case 400:
errRes.Error.ErrorType = BadRequestError
case 401:
errRes.Error.ErrorType = UnauthorizedError
case 403:
errRes.Error.ErrorType = ForbiddenError
case 404:
errRes.Error.ErrorType = NotFoundError
case 500:
errRes.Error.ErrorType = InternalServerError
default:
errRes.Error.ErrorType = GenericError
}
return &errRes.Error
}
func (e *errorResponse) Error() string {
return string(e.ErrorType) + ": " + e.Message
}
func (e *errorResponse) StatusCode() int {
return e.Status
}
func (e *errorResponse) Type() ErrorType {
return e.ErrorType
}
func (e *errorResponse) ApiErrorType() string {
return e.ApiType
}