File: errors.go

package info (click to toggle)
golang-github-nrdcg-desec 0.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 228 kB
  • sloc: makefile: 13
file content (67 lines) | stat: -rw-r--r-- 1,309 bytes parent folder | download
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))}
}