-
Notifications
You must be signed in to change notification settings - Fork 65
/
with_hint.go
72 lines (61 loc) · 2.16 KB
/
with_hint.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
70
71
72
// Copyright 2019 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package hintdetail
import (
"context"
"fmt"
"github.com/cockroachdb/errors/errbase"
"github.com/cockroachdb/errors/errorspb"
"github.com/gogo/protobuf/proto"
)
type withHint struct {
cause error
hint string
}
var _ error = (*withHint)(nil)
var _ ErrorHinter = (*withHint)(nil)
var _ fmt.Formatter = (*withHint)(nil)
var _ errbase.Formatter = (*withHint)(nil)
func (w *withHint) ErrorHint() string { return w.hint }
func (w *withHint) Error() string { return w.cause.Error() }
func (w *withHint) Cause() error { return w.cause }
func (w *withHint) Unwrap() error { return w.cause }
func (w *withHint) Format(s fmt.State, verb rune) { errbase.FormatError(w, s, verb) }
func (w *withHint) FormatError(p errbase.Printer) error {
if p.Detail() {
p.Print(w.hint)
}
return w.cause
}
func encodeWithHint(_ context.Context, err error) (string, []string, proto.Message) {
w := err.(*withHint)
return "", nil, &errorspb.StringPayload{Msg: w.hint}
}
func decodeWithHint(
_ context.Context, cause error, _ string, _ []string, payload proto.Message,
) error {
m, ok := payload.(*errorspb.StringPayload)
if !ok {
// If this ever happens, this means some version of the library
// (presumably future) changed the payload type, and we're
// receiving this here. In this case, give up and let
// DecodeError use the opaque type.
return nil
}
return &withHint{cause: cause, hint: m.Msg}
}
func init() {
errbase.RegisterWrapperEncoder(errbase.GetTypeKey((*withHint)(nil)), encodeWithHint)
errbase.RegisterWrapperDecoder(errbase.GetTypeKey((*withHint)(nil)), decodeWithHint)
}