-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
117 lines (101 loc) · 2.45 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package jsonhttpc
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
)
var (
// ErrEmptyResponse is received empty response unexpectedly.
// Ex. StatusCode shows success but Content-Length is 0.
// This is a server side error.
ErrEmptyResponse = errors.New("unexpected empty response")
// ErrReceiverAbsence means `receiver` is nil.
// Server responded with body, but user did't provide any receivers.
// This is a user side error.
ErrReceiverAbsence = errors.New("receiver absence")
)
// SystemError is for problems on jsonhttp.
type SystemError struct {
StatusCode int
Status string
Err error
}
var _ error = (*SystemError)(nil)
func newSystemError(r *http.Response, err error) error {
return &SystemError{
StatusCode: r.StatusCode,
Status: r.Status,
Err: err,
}
}
func (se *SystemError) Error() string {
return fmt.Sprintf("jsonhttpc system problem: %s: %s", se.Status, se.Err)
}
// Unwrap obtains the based error.
func (se *SystemError) Unwrap() error {
return se.Err
}
// Error is general structure to store error.
// This supports https://tools.ietf.org/html/rfc7807, if "status" field has
// some troubles (not string or differ from `StatusCode`, its raw value is put
// into `Properties`.
type Error struct {
StatusCode int
Status string
ContentType string
Type string
Title string
Detail string
Instance string
Properties map[string]interface{}
}
var _ error = (*Error)(nil)
func parseError(r *http.Response) (*Error, error) {
er := &Error{
StatusCode: r.StatusCode,
Status: r.Status,
ContentType: r.Header.Get("Content-Type"),
}
var props map[string]interface{}
err := json.NewDecoder(r.Body).Decode(&props)
if err != nil {
return nil, newSystemError(r, fmt.Errorf("failed to decode error JSON: %w", err))
}
for k, v := range props {
var del bool
switch k {
case "type":
er.Type = fmt.Sprint(v)
del = true
case "title":
er.Title = fmt.Sprint(v)
del = true
case "status":
n, err := strconv.Atoi(fmt.Sprint(v))
if err != nil {
continue
}
if er.StatusCode != n {
continue
}
del = true
case "detail":
er.Detail = fmt.Sprint(v)
del = true
case "instance":
er.Instance = fmt.Sprint(v)
del = true
}
if del {
delete(props, k)
}
}
er.Properties = props
return er, nil
}
// Error returns error message.
func (er *Error) Error() string {
return fmt.Sprintf("error: status=%q props=%#v", er.Status, er.Properties)
}