-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathapi_error.go
61 lines (54 loc) · 1.4 KB
/
api_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
57
58
59
60
61
package soracom
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
// APIError represents an error ocurred while calling API
type APIError struct {
HTTPStatusCode int
ErrorCode string
Message string
}
type apiErrorResponse struct {
ErrorCode string `json:"code"`
Message string `json:"message"`
MessageArgs string `json:"messageArgs"`
}
func parseAPIErrorResponse(resp *http.Response) *apiErrorResponse {
var aer apiErrorResponse
dec := json.NewDecoder(resp.Body)
_ = dec.Decode(&aer)
return &aer
}
// NewAPIError creates an instance of APIError from http.Response
func NewAPIError(resp *http.Response) *APIError {
var errorCode, message string
ct := resp.Header.Get("Content-Type")
if strings.Index(ct, "text/plain") == 0 {
errorCode = "UNK0001"
message = readAll(resp.Body)
} else if strings.Index(ct, "application/json") == 0 {
if resp.StatusCode >= http.StatusBadRequest &&
resp.StatusCode < http.StatusInternalServerError {
aer := parseAPIErrorResponse(resp)
errorCode = aer.ErrorCode
message = fmt.Sprintf(aer.Message, aer.MessageArgs)
} else {
errorCode = ""
message = readAll(resp.Body)
}
} else {
errorCode = "INT0001"
message = "Content-Type: " + ct + " is not supported"
}
return &APIError{
HTTPStatusCode: resp.StatusCode,
ErrorCode: errorCode,
Message: message,
}
}
func (ae *APIError) Error() string {
return ae.Message
}