-
Notifications
You must be signed in to change notification settings - Fork 0
/
error.go
69 lines (56 loc) · 1.52 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package mrpc
import (
"context"
"fmt"
)
// ErrorCode determines the error code of the given error.
func ErrorCode(err error) ErrCode {
switch err {
case nil:
return OK
case context.DeadlineExceeded:
return Timeout
}
if e, ok := err.(interface{ ErrorCode() ErrCode }); ok {
return e.ErrorCode()
}
return Unknown
}
// Error returns an error with the given code and error text. If code
// is OK, nil will be returned.
func Error(code ErrCode, text string) error {
if code == OK {
return nil
}
return codeError{code: code, text: text}
}
// Errorf returns an error with the given code and the formatted error
// text. If code is OK, nil will be returned.
func Errorf(code ErrCode, format string, args ...interface{}) error {
return Error(code, fmt.Sprintf(format, args...))
}
// ResponseError returns the error for the given response.
func ResponseError(resp Response) error {
return Error(resp.ErrorCode, resp.ErrorText)
}
// ErrorResponse returns a response which indicates the given error.
func ErrorResponse(err error) Response {
return Response{ErrorCode: ErrorCode(err), ErrorText: err.Error()}
}
func ErrorResponsef(code ErrCode, format string, args ...interface{}) Response {
return Response{ErrorCode: code, ErrorText: fmt.Sprintf(format, args...)}
}
type codeError struct {
code ErrCode
text string
}
func (e codeError) ErrorCode() ErrCode {
return e.code
}
func (e codeError) Error() string {
return e.text
}
type optionError string
func (e optionError) Error() string {
return "invalid option: " + string(e)
}