-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
73 lines (62 loc) · 1.48 KB
/
errors.go
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
package errors
import (
"encoding/json"
"errors"
"net/http"
)
// APIError - error interface
type APIError interface {
Status() int
Message() string
Error() string
}
type apiError struct {
ErrStatus int `json:"status"`
ErrMessage string `json:"message"`
ErrErr string `json:"error,omitempty"`
}
func (e *apiError) Status() int {
return e.ErrStatus
}
func (e *apiError) Message() string {
return e.ErrMessage
}
func (e *apiError) Error() string {
return e.ErrErr
}
// NewAPIErrorFromBytes - raised when testing json of bytes array
func NewAPIErrorFromBytes(body []byte) (APIError, error) {
var res apiError
if err := json.Unmarshal(body, &res); err != nil {
return nil, errors.New("invalid json body")
}
return &res, nil
}
// NewNotFoundAPIError - raised on a not found case
func NewNotFoundAPIError(message string) APIError {
return &apiError{
ErrStatus: http.StatusNotFound,
ErrMessage: message,
}
}
// NewInternalServerError - raised on an internal server error
func NewInternalServerError(message string) APIError {
return &apiError{
ErrStatus: http.StatusInternalServerError,
ErrMessage: message,
}
}
// NewBadRequestAPIError - raised for a bad request
func NewBadRequestAPIError(message string) APIError {
return &apiError{
ErrStatus: http.StatusBadRequest,
ErrMessage: message,
}
}
// NewAPIError for untrapped errors
func NewAPIError(statusCode int, message string) APIError {
return &apiError{
ErrStatus: statusCode,
ErrMessage: message,
}
}