forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vterrors.go
59 lines (50 loc) · 1.31 KB
/
vterrors.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
package vterrors
import (
"fmt"
"time"
"golang.org/x/net/context"
"github.com/youtube/vitess/go/tb"
"github.com/youtube/vitess/go/vt/logutil"
vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)
var logger = logutil.NewThrottledLogger("vterror", 5*time.Second)
type vtError struct {
code vtrpcpb.Code
err string
}
// New creates a new error using the code and input string.
func New(code vtrpcpb.Code, in string) error {
if code == vtrpcpb.Code_OK {
logger.Errorf("OK is an invalid code, using INTERNAL instead: %s\n%s", in, tb.Stack(2))
code = vtrpcpb.Code_INTERNAL
}
return &vtError{
code: code,
err: in,
}
}
// Errorf returns a new error built using Printf style arguments.
func Errorf(code vtrpcpb.Code, format string, args ...interface{}) error {
return New(code, fmt.Sprintf(format, args...))
}
func (e *vtError) Error() string {
return e.err
}
// Code returns the error code if it's a vtError.
// If err is nil, it returns ok. Otherwise, it returns unknown.
func Code(err error) vtrpcpb.Code {
if err == nil {
return vtrpcpb.Code_OK
}
if err, ok := err.(*vtError); ok {
return err.code
}
// Handle some special cases.
switch err {
case context.Canceled:
return vtrpcpb.Code_CANCELED
case context.DeadlineExceeded:
return vtrpcpb.Code_DEADLINE_EXCEEDED
}
return vtrpcpb.Code_UNKNOWN
}