-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
error.go
60 lines (54 loc) · 1.1 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
57
58
59
60
package sdk
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
)
// Error API error.
type Error struct {
HTTPCode int
errorResp
}
func (e Error) Error() string {
return "[HTTP Code: " + strconv.Itoa(e.HTTPCode) + "][Error Code: " + e.Code + "] " + e.Message
}
func (e Error) httpResp() *http.Response {
o, _ := json.Marshal(e.errorResp)
return &http.Response{
Status: e.Code,
StatusCode: e.HTTPCode,
Body: io.NopCloser(bytes.NewReader(o)),
ContentLength: int64(len(o)),
}
}
type errorResp struct {
Code string `json:"code"`
Message string `json:"message"`
}
func convertErrorResponse(res *http.Response) error {
var v errorResp
buf, err := io.ReadAll(res.Body)
defer func() { _ = res.Body.Close() }()
if err != nil {
return Error{
HTTPCode: res.StatusCode,
errorResp: errorResp{
Message: "cannot read response bytes",
},
}
}
if err := json.Unmarshal(buf, &v); err != nil {
return Error{
HTTPCode: res.StatusCode,
errorResp: errorResp{
Message: err.Error(),
},
}
}
return Error{
HTTPCode: res.StatusCode,
errorResp: v,
}
}