forked from signalfx/signalfx-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
80 lines (67 loc) · 1.78 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 signalfx
import (
"errors"
"fmt"
"io"
"net/http"
"slices"
)
// ResponseError captures the error details
// and allows for it to be inspected by external libraries.
type ResponseError struct {
code int
route string
details string
}
var _ error = (*ResponseError)(nil)
func newResponseError(resp *http.Response, target int, targets ...int) error {
if resp == nil {
return nil
}
if slices.Contains(append([]int{target}, targets...), resp.StatusCode) {
return nil
}
details, _ := io.ReadAll(resp.Body)
return &ResponseError{
code: resp.StatusCode,
route: resp.Request.URL.Path,
details: string(details),
}
}
// AsResponseError is a convenience function to check the error
// to see if it contains an `ResponseError` and returns the value with true.
// If the error was initially joined using [errors.Join], it will check each error
// within the list and return the first matching error.
func AsResponseError(err error) (*ResponseError, bool) {
// When `errors.Join` is called, it returns an error that
// matches the provided interface.
if joined, ok := err.(interface{ Unwrap() []error }); ok {
for _, err := range joined.Unwrap() {
if re, ok := AsResponseError(err); ok {
return re, ok
}
}
return nil, false
}
for err != nil {
if re, ok := err.(*ResponseError); ok {
return re, true
}
// In case the error is wrapped using `fmt.Errorf`
// this will also account for that.
err = errors.Unwrap(err)
}
return nil, false
}
func (re *ResponseError) Error() string {
return fmt.Sprintf("route %q had issues with status code %d", re.route, re.code)
}
func (re *ResponseError) Code() int {
return re.code
}
func (re *ResponseError) Route() string {
return re.route
}
func (re *ResponseError) Details() string {
return re.details
}