-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
66 lines (59 loc) · 1.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
package models
import (
"errors"
"fmt"
)
type ErrorCode int32
const (
Unknown ErrorCode = iota
Internal
InvalidArgument
Unauthenticated
Conflict
NotFound
Canceled
DeadlineExceeded
PermissionDenied
)
type ServiceError struct {
Msg string
Code ErrorCode
}
func (t ErrorCode) String() string {
switch t {
case Internal:
return "Internal"
case InvalidArgument:
return "InvalidArgument"
case Unauthenticated:
return "Unauthenticated"
case Conflict:
return "Conflict"
case NotFound:
return "NotFound"
case Canceled:
return "Canceled"
case DeadlineExceeded:
return "DeadlineExceeded"
case PermissionDenied:
return "PermissionDenied"
default:
return "Unknown"
}
}
func (e *ServiceError) Error() string {
return fmt.Sprintf("%s %s", e.Code, e.Msg)
}
func Code(err error) ErrorCode {
srvErr := &ServiceError{}
if errors.As(err, &srvErr) {
return srvErr.Code
}
return Unknown
}
func Error(code ErrorCode, msg string) *ServiceError {
return &ServiceError{Code: code, Msg: msg}
}
func Errorf(code ErrorCode, format string, a ...any) *ServiceError {
return &ServiceError{Code: code, Msg: fmt.Sprintf(format, a...)}
}