-
Notifications
You must be signed in to change notification settings - Fork 0
/
gr_err.go
54 lines (44 loc) · 1.4 KB
/
gr_err.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
package gr
import "strconv"
/*
Wraps another error, adding an HTTP status code and response body. Some errors
returned by this package have codes obtained from `http.Response`.
*/
type Err struct {
Status int `json:"status,omitempty"`
Body []byte `json:"body,omitempty"`
Cause error `json:"cause,omitempty"`
}
// ↑ TODO: preserve other response data such as headers. Consider defining a
// type describing a fully downloaded response.
// Implement a hidden interface in "errors".
func (self Err) Unwrap() error { return self.Cause }
// Returns `.Status`. Implements a hidden interface supported by
// `github.com/mitranim/rout`.
func (self Err) HttpStatusCode() int { return self.Status }
// Implement the `error` interface.
func (self Err) Error() string {
return bytesString(self.AppendTo(nil))
}
// Appends the error representation. Used internally by `.Error`.
func (self Err) AppendTo(buf []byte) []byte {
buf = growBytes(buf, 128)
buf = append(buf, `[gr] error`...)
if self.Status != 0 {
buf = append(buf, ` (HTTP status `...)
buf = strconv.AppendInt(buf, int64(self.Status), 10)
buf = append(buf, `)`...)
}
cause := self.Cause
if cause != nil {
buf = append(buf, `: `...)
impl, _ := cause.(interface{ AppendTo([]byte) []byte })
if impl != nil {
buf = impl.AppendTo(buf)
} else {
buf = append(buf, cause.Error()...)
}
}
buf = appendBodyPreview(buf, self.Body)
return buf
}