-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapperr.go
More file actions
57 lines (48 loc) · 1.36 KB
/
apperr.go
File metadata and controls
57 lines (48 loc) · 1.36 KB
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
package apperr
import (
"fmt"
"runtime"
)
// Component defines where the error occurred
type Component string
const (
DataLayer Component = "DataLayer"
LogicLayer Component = "LogicLayer"
APILayer Component = "APILayer"
)
// AppError is our custom error type
type AppError struct {
Component Component // Where it failed
PublicMessage string // Safe to show to the end-user
OriginalErr error // The actual error that triggered this
File string // Traceback: File name
Line int // Traceback: Line number
}
// New creates a new AppError and captures the caller's traceback automatically
func New(comp Component, publicMsg string, err error) *AppError {
_, file, line, ok := runtime.Caller(1)
if !ok {
file = "unknown"
line = 0
}
return &AppError{
Component: comp,
PublicMessage: publicMsg,
OriginalErr: err,
File: file,
Line: line,
}
}
func (e *AppError) Error() string {
if e.OriginalErr != nil {
return fmt.Sprintf("[%s] %s:%d - %s: %v", e.Component, e.File, e.Line, e.PublicMessage, e.OriginalErr)
}
return fmt.Sprintf("[%s] %s:%d - %s", e.Component, e.File, e.Line, e.PublicMessage)
}
func (e *AppError) Unwrap() error {
return e.OriginalErr
}
// ClientError provides the safe message for the API/CLI response.
func (e *AppError) ClientError() string {
return e.PublicMessage
}