This repository has been archived by the owner on Jul 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
errorz.go
63 lines (57 loc) · 1.52 KB
/
errorz.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
package errorz
import (
"context"
"encoding/json"
"github.com/stategate/stategate/internal/logger"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Type int
const (
ErrUnknown Type = 0
ErrUnauthenticated Type = 1
ErrUnauthorized Type = 2
ErrNotFound Type = 5
ErrTimeout Type = 6
ErrLocked Type = 7
)
type Error struct {
Type Type `json:"type"`
Info string `json:"info"`
Err error `json:"err"`
Metadata map[string]string `json:"metadata"`
}
func (e Error) Public() error {
data := map[string]interface{}{
"type": e.Type,
"info": e.Info,
"metadata": e.Metadata,
}
bits, _ := json.Marshal(&data)
switch e.Type {
case ErrNotFound:
return status.Error(codes.NotFound, string(bits))
case ErrUnauthenticated:
return status.Error(codes.Unauthenticated, string(bits))
case ErrUnauthorized:
return status.Error(codes.PermissionDenied, string(bits))
case ErrUnknown:
return status.Error(codes.Internal, string(bits))
case ErrTimeout:
return status.Error(codes.DeadlineExceeded, string(bits))
case ErrLocked:
return status.Error(codes.AlreadyExists, string(bits))
default:
if e.Err == context.Canceled {
return status.Error(codes.DeadlineExceeded, string(bits))
}
return status.Error(codes.Internal, string(bits))
}
}
func (e Error) Log(logger *logger.Logger) {
logger.Error(e.Info,
zap.Int("type", int(e.Type)),
zap.Error(e.Err),
zap.Any("metadata", e.Metadata))
}