-
Notifications
You must be signed in to change notification settings - Fork 14
/
errors.go
112 lines (87 loc) · 2.13 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
package lua
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/krakendio/binder"
)
type ErrWrongChecksumType string
func (e ErrWrongChecksumType) Error() string {
return "lua: wrong cheksum type for source " + string(e)
}
type ErrWrongChecksum struct {
Source, Actual, Expected string
}
func (e ErrWrongChecksum) Error() string {
return fmt.Sprintf("lua: wrong cheksum for source %s. have: %v, want: %v", e.Source, e.Actual, e.Expected)
}
type ErrUnknownSource string
func (e ErrUnknownSource) Error() string {
return "lua: unable to load required source " + string(e)
}
var errNeedsArguments = errors.New("need arguments")
type ErrInternal string
func (e ErrInternal) Error() string {
return string(e)
}
type ErrInternalHTTP struct {
msg string
code int
}
func (e ErrInternalHTTP) StatusCode() int {
return e.code
}
func (e ErrInternalHTTP) Error() string {
return e.msg
}
type ErrInternalHTTPWithContentType struct {
ErrInternalHTTP
contentType string
}
func (e ErrInternalHTTPWithContentType) Encoding() string {
return e.contentType
}
const separator = " || "
func ToError(e error) error {
if e == nil {
return nil
}
if _, ok := e.(*binder.Error); !ok {
return e
}
originalMsg := e.Error()
errMsgParts := strings.Split(originalMsg[strings.Index(originalMsg, ":")+2:], separator)
if len(errMsgParts) == 0 {
return e
}
if len(errMsgParts) == 1 {
return ErrInternal(errMsgParts[0])
}
code, err := strconv.Atoi(errMsgParts[1])
if err != nil {
code = 500
}
errHTTP := ErrInternalHTTP{msg: errMsgParts[0], code: code}
if len(errMsgParts) == 2 {
return errHTTP
}
return ErrInternalHTTPWithContentType{
ErrInternalHTTP: errHTTP,
contentType: errMsgParts[2],
}
}
func RegisterErrors(b *binder.Binder) {
b.Func("custom_error", func(c *binder.Context) error {
switch c.Top() {
case 0:
return errNeedsArguments
case 1:
return errors.New(c.Arg(1).String())
case 2:
return fmt.Errorf("%s%s%d", c.Arg(1).String(), separator, int(c.Arg(2).Number()))
default:
return fmt.Errorf("%s%s%d%s%s", c.Arg(1).String(), separator, int(c.Arg(2).Number()), separator, c.Arg(3).String())
}
})
}