-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
80 lines (71 loc) · 1.36 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
74
75
76
77
78
79
80
package chttp
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
var (
ErrStatusCode = fmt.Errorf("wrong status code")
ErrUnknown = fmt.Errorf("unknown error")
)
type Error struct {
Response *http.Response
Body []byte
Base error
}
func newError(response *http.Response, body []byte, err error) *Error {
return &Error{
Response: response,
Body: body,
Base: err,
}
}
func (e *Error) IsStatusCode() bool {
if e == nil {
return false
}
if e.Base != nil {
return false
}
if e.Response != nil {
return e.Response.StatusCode >= http.StatusMultipleChoices
}
return false
}
func (e *Error) Error() string {
if e == nil {
return ""
}
return e.Unwrap().Error()
}
func (e *Error) Unwrap() error {
if e.Base != nil {
return e.Base
}
if e.Response != nil {
return fmt.Errorf("%w, status_code=%d", ErrStatusCode, e.Response.StatusCode)
}
return ErrUnknown
}
func (e *Error) UnmarshalTo(value interface{}) (bool, error) {
if e.IsStatusCode() {
err := json.Unmarshal(e.Body, &value)
if err != nil {
return false, err
}
return true, nil
}
return false, nil
}
func ErrorUnmarshalTo[Result any](err error) (result Result, _ error) {
base := new(Error)
if errors.As(err, &base) {
if ok, err := base.UnmarshalTo(&result); err != nil {
return result, err
} else if ok {
return result, nil
}
}
return result, err
}