-
Notifications
You must be signed in to change notification settings - Fork 224
/
flaps_error.go
110 lines (89 loc) · 2.08 KB
/
flaps_error.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package flaps
import (
"encoding/json"
"errors"
"net/http"
)
var (
FlapsErrorNotFound = &FlapsError{ResponseStatusCode: http.StatusNotFound}
)
type StatusCode string
const (
unknown StatusCode = "unknown"
regionOOCapacity StatusCode = "insufficient_capacity"
)
type errorResponse struct {
Error string `json:"error"`
StatusCode StatusCode `json:"status"`
}
type FlapsError struct {
OriginalError error
ResponseStatusCode int
ResponseBody []byte
FlyRequestId string
}
func (fe *FlapsError) Error() string {
if fe.OriginalError == nil {
return ""
}
return fe.OriginalError.Error()
}
func (fe *FlapsError) Suggestion() string {
statusCode := fe.StatusCode()
if statusCode == nil {
return ""
}
switch *statusCode {
case unknown:
return ""
case regionOOCapacity:
// TODO(billy): once we have support for 'backup regions', suggest creating adding those (or eveven better, just do it automatically)
return "Try choosing a different region for machine creation"
}
return ""
}
type ErrorStatusCode interface {
error
StatusCode() *StatusCode
}
func GetErrorStatusCode(err error) *StatusCode {
var ferr ErrorStatusCode
if errors.As(err, &ferr) {
return ferr.StatusCode()
}
return nil
}
// TODO: we might not actually need an interface type here
type ErrorRequestID interface {
ErrRequestID() string
}
func GetErrorRequestID(err error) string {
var ferr ErrorRequestID
if errors.As(err, &ferr) {
return ferr.ErrRequestID()
}
return ""
}
func (fe *FlapsError) StatusCode() *StatusCode {
var errResp errorResponse
unmarshalErr := json.Unmarshal(fe.ResponseBody, &errResp)
if unmarshalErr != nil {
return nil
}
return &errResp.StatusCode
}
func (fe *FlapsError) ErrRequestID() string {
return fe.FlyRequestId
}
func (fe *FlapsError) Is(target error) bool {
if other, ok := target.(*FlapsError); ok {
return fe.ResponseStatusCode == other.ResponseStatusCode
}
return false
}
func (fe *FlapsError) Unwrap() error {
return fe.OriginalError
}
func (fe *FlapsError) ResponseBodyString() string {
return string(fe.ResponseBody)
}