forked from contraband/gaol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
116 lines (93 loc) · 2.14 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package garden
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
type errType string
const (
unrecoverableErrType = "UnrecoverableError"
serviceUnavailableErrType = "ServiceUnavailableError"
containerNotFoundErrType = "ContainerNotFoundError"
)
type Error struct {
Err error
}
func NewError(err string) *Error {
return &Error{Err: errors.New(err)}
}
type marshalledError struct {
Type errType
Message string
Handle string
}
func (m Error) Error() string {
return m.Err.Error()
}
func (m Error) StatusCode() int {
switch m.Err.(type) {
case ContainerNotFoundError:
return http.StatusNotFound
}
return http.StatusInternalServerError
}
func (m Error) MarshalJSON() ([]byte, error) {
var errorType errType
handle := ""
switch err := m.Err.(type) {
case ContainerNotFoundError:
errorType = containerNotFoundErrType
handle = err.Handle
case ServiceUnavailableError:
errorType = serviceUnavailableErrType
case UnrecoverableError:
errorType = unrecoverableErrType
}
return json.Marshal(marshalledError{errorType, m.Err.Error(), handle})
}
func (m *Error) UnmarshalJSON(data []byte) error {
var result marshalledError
if err := json.Unmarshal(data, &result); err != nil {
return err
}
switch result.Type {
case unrecoverableErrType:
m.Err = UnrecoverableError{result.Message}
case serviceUnavailableErrType:
m.Err = ServiceUnavailableError{result.Message}
case containerNotFoundErrType:
m.Err = ContainerNotFoundError{result.Handle}
default:
m.Err = errors.New(result.Message)
}
return nil
}
func NewUnrecoverableError(symptom string) error {
return UnrecoverableError{
Symptom: symptom,
}
}
type UnrecoverableError struct {
Symptom string
}
func (err UnrecoverableError) Error() string {
return err.Symptom
}
type ContainerNotFoundError struct {
Handle string
}
func (err ContainerNotFoundError) Error() string {
return fmt.Sprintf("unknown handle: %s", err.Handle)
}
func NewServiceUnavailableError(cause string) error {
return ServiceUnavailableError{
Cause: cause,
}
}
type ServiceUnavailableError struct {
Cause string
}
func (err ServiceUnavailableError) Error() string {
return err.Cause
}