-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
53 lines (44 loc) · 1.07 KB
/
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
package trompe
import "fmt"
const (
GenericError = iota
InvalidArityError
KeyError
)
type RuntimeError struct {
Context *Context
Type int
Reason string
}
func ErrorName(ty int) string {
switch ty {
case GenericError:
return "GenericError"
case InvalidArityError:
return "InvalidArityError"
default:
panic("unknown error")
}
}
func NewRuntimeError(ctx *Context, ty int, reason string) *RuntimeError {
return &RuntimeError{ctx, ty, reason}
}
func (err *RuntimeError) Error() string {
return fmt.Sprintf("%s: %s", ErrorName(err.Type), err.Reason)
}
func NewInvalidArityError(ctx *Context, nargs int) *RuntimeError {
return NewRuntimeError(ctx, InvalidArityError, "")
}
func NewKeyError(ctx *Context, name string) *RuntimeError {
return NewRuntimeError(ctx, KeyError,
fmt.Sprintf("key %s not found", name))
}
func ValidateArity(ctx *Context, expected int, actual int) *RuntimeError {
if expected != actual {
return NewRuntimeError(ctx,
InvalidArityError,
fmt.Sprintf("invalid arity (takes %d, but %d given)", expected, actual))
} else {
return nil
}
}