errors.go raw
1 package desec
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 )
9
10 // NotFoundError Not found error.
11 type NotFoundError struct {
12 Detail string `json:"detail"`
13 }
14
15 func (n NotFoundError) Error() string {
16 return n.Detail
17 }
18
19 // APIError error from API.
20 type APIError struct {
21 StatusCode int
22 err error
23 }
24
25 func (e APIError) Error() string {
26 return fmt.Sprintf("%d: %v", e.StatusCode, e.err)
27 }
28
29 // Unwrap unwraps error.
30 func (e APIError) Unwrap() error {
31 return e.err
32 }
33
34 func readError(resp *http.Response, er error) error {
35 body, err := io.ReadAll(resp.Body)
36 if err != nil {
37 return &APIError{
38 StatusCode: resp.StatusCode,
39 err: fmt.Errorf("failed to read response body: %w", err),
40 }
41 }
42
43 err = json.Unmarshal(body, er)
44 if err != nil {
45 return &APIError{
46 StatusCode: resp.StatusCode,
47 err: fmt.Errorf("failed to unmarshall response body: %w: %s", err, string(body)),
48 }
49 }
50
51 return &APIError{
52 StatusCode: resp.StatusCode,
53 err: er,
54 }
55 }
56
57 func readRawError(resp *http.Response) error {
58 body, err := io.ReadAll(resp.Body)
59 if err != nil {
60 return &APIError{
61 StatusCode: resp.StatusCode,
62 err: fmt.Errorf("failed to read response body: %w", err),
63 }
64 }
65
66 return &APIError{StatusCode: resp.StatusCode, err: fmt.Errorf("body: %s", string(body))}
67 }
68