/
errors.go
91 lines (72 loc) · 1.77 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
81
82
83
84
85
86
87
88
89
90
91
package topolib
import (
"encoding/json"
"errors"
"net/http"
)
var (
// ErrTopographerShutdown returns if you've tried to resolve ips via
// topographer but instance was shutdown.
ErrTopographerShutdown = errors.New("topographer instance was shutdown")
// ErrContextIsClosed returns if context is closed during execution
// of the method.
ErrContextIsClosed = errors.New("context is closed")
// ErrCircuitBreakerOpened returns by http client if circuit breaker
// is opened.
ErrCircuitBreakerOpened = errors.New("circuit breaker is opened")
// ErrCircuitBreakerIgnore should be returned if it is necessary to
// ignore circuit breaker error in http client.
ErrCircuitBreakerIgnore = errors.New("this error should be ignores by circuit breaker")
)
type jsonHTTPError struct {
Error struct {
Message string `json:"message"`
Context string `json:"context"`
} `json:"error"`
}
type httpError struct {
message string
err error
statusCode int
}
func (h *httpError) Message() string {
if h == nil {
return ""
}
return h.message
}
func (h *httpError) Err() string {
if err := errors.Unwrap(h); err != nil {
return err.Error()
}
return ""
}
func (h *httpError) StatusCode() int {
if h != nil && h.statusCode != 0 {
return h.statusCode
}
return http.StatusInternalServerError
}
func (h *httpError) Unwrap() error {
if h == nil {
return nil
}
return h.err
}
func (h *httpError) Error() string {
switch {
case h == nil:
return ""
case h.err != nil && h.message != "":
return h.message + ": " + h.err.Error()
case h.err != nil:
return h.err.Error()
}
return h.message
}
func (h *httpError) MarshalJSON() ([]byte, error) {
value := jsonHTTPError{}
value.Error.Message = h.Message()
value.Error.Context = h.Err()
return json.Marshal(&value)
}