/
error.go
56 lines (47 loc) · 1.52 KB
/
error.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
package bcccoreapi
import (
"encoding/json"
"fmt"
"net/http"
)
type Error struct {
Code ErrorCode `json:"code"`
Message string `json:"message"`
}
type ErrorCode string
const (
ErrorCodeNotFound ErrorCode = "not-found"
ErrorCodeInvalidQuery ErrorCode = "invalid-query"
ErrorCodeInvalidBody ErrorCode = "invalid-body"
ErrorCodeInvalidKeyReference ErrorCode = "invalid-key-reference"
ErrorCodeDuplicateUniqueKey ErrorCode = "duplicate-unique-key"
ErrorCodeCannotParseToken ErrorCode = "cannot-parse-token"
ErrorCodeInvalidToken ErrorCode = "invalid-token"
ErrorCodeMissingScopes ErrorCode = "missing-scopes"
ErrorCodeInternalError ErrorCode = "internal-error"
ErrorCodeUnauthorized ErrorCode = "unauthorized"
ErrorCodeInvalidAppUID ErrorCode = "invalid-app-uid"
ErrorCodeUnknownErrorResponse ErrorCode = "unknown-error-response"
)
type errorResponse struct {
Error Error `json:"error"`
}
func newError(response *http.Response) error {
apiError := &errorResponse{}
if err := json.NewDecoder(response.Body).Decode(apiError); err != nil {
err = fmt.Errorf("%d %s:failed to decode json error response payload: %w",
response.StatusCode,
http.StatusText(response.StatusCode),
err,
)
return &Error{
Code: ErrorCodeUnknownErrorResponse,
Message: err.Error(),
}
}
return &apiError.Error
}
// Error formats the error into a string representation.
func (m *Error) Error() string {
return fmt.Sprintf("%s: %s", m.Code, m.Message)
}