forked from sourcegraph/sourcegraph-public-snapshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpresentation_error.go
72 lines (63 loc) · 2.25 KB
/
presentation_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
70
71
72
package errcode
// A PresentationError is an error with a message (returned by the PresentationError method) that is
// suitable for presentation to the user.
type PresentationError interface {
error
// PresentationError returns the message suitable for presentation to the user. The message
// should be written in full sentences and must not contain any information that the user is not
// authorized to see.
PresentationError() string
}
// WithPresentationMessage annotates err with a new message suitable for presentation to the
// user. If err is nil, WithPresentationMessage returns nil. Otherwise, the return value implements
// PresentationError.
//
// The message should be written in full sentences and must not contain any information that the
// user is not authorized to see.
func WithPresentationMessage(err error, message string) error {
if err == nil {
return nil
}
return &presentationError{cause: err, msg: message}
}
// NewPresentationError returns a new error with a message suitable for presentation to the user.
// The message should be written in full sentences and must not contain any information that the
// user is not authorized to see.
//
// If there is an underlying error associated with this message, use WithPresentationMessage
// instead.
func NewPresentationError(message string) error {
return &presentationError{cause: nil, msg: message}
}
// presentationError implements PresentationError.
type presentationError struct {
cause error
msg string
}
func (e *presentationError) Error() string {
if e.cause != nil {
return e.cause.Error()
}
return e.msg
}
func (e *presentationError) PresentationError() string { return e.msg }
// PresentationMessage returns the message, if any, suitable for presentation to the user for err or
// one of its causes. An error provides a presentation message by implementing the PresentationError
// interface (e.g., by using WithPresentationMessage). If no presentation message exists for err,
// the empty string is returned.
func PresentationMessage(err error) string {
type causer interface {
Cause() error
}
for err != nil {
if e, ok := err.(PresentationError); ok {
return e.PresentationError()
}
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return ""
}