-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
errors.go
67 lines (56 loc) · 1.28 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
package desec
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
// NotFoundError Not found error.
type NotFoundError struct {
Detail string `json:"detail"`
}
func (n NotFoundError) Error() string {
return n.Detail
}
// APIError error from API.
type APIError struct {
StatusCode int
err error
}
func (e APIError) Error() string {
return fmt.Sprintf("%d: %v", e.StatusCode, e.err)
}
// Unwrap unwraps error.
func (e APIError) Unwrap() error {
return e.err
}
func readError(resp *http.Response, er error) error {
body, err := io.ReadAll(resp.Body)
if err != nil {
return &APIError{
StatusCode: resp.StatusCode,
err: fmt.Errorf("failed to read response body: %w", err),
}
}
err = json.Unmarshal(body, er)
if err != nil {
return &APIError{
StatusCode: resp.StatusCode,
err: fmt.Errorf("failed to unmarshall response body: %w: %s", err, string(body)),
}
}
return &APIError{
StatusCode: resp.StatusCode,
err: er,
}
}
func readRawError(resp *http.Response) error {
body, err := io.ReadAll(resp.Body)
if err != nil {
return &APIError{
StatusCode: resp.StatusCode,
err: fmt.Errorf("failed to read response body: %w", err),
}
}
return &APIError{StatusCode: resp.StatusCode, err: fmt.Errorf("body: %s", string(body))}
}