-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_log_test.go
189 lines (162 loc) · 6.33 KB
/
example_log_test.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package errors_test
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"log"
"strings"
"github.com/muonsoft/errors"
"github.com/muonsoft/errors/errorstest"
)
var (
// Use errors.New() only for sentinel errors at package level.
// It would not add a stack trace.
ErrNotFound = errors.New("not found")
errSQLError = errors.New("sql error")
)
// To initiate a sentinel error with a stack trace it is recommended to use a
// constructor function and wrap the error with errors.Wrap().
// Use errors.SkipCaller() option to remove constructor function from a stack trace.
func newNotFoundError() error {
return errors.Wrap(ErrNotFound, errors.SkipCaller())
}
type Product struct {
ID int
Name string
}
type SQLDriver struct {
err error
}
type Row struct {
err error
}
func (row *Row) Scan(dest ...interface{}) error {
return row.err
}
func (driver *SQLDriver) QueryRow(ctx context.Context, sql string, arguments ...interface{}) *Row {
return &Row{err: driver.err}
}
type ProductRepository struct {
db *SQLDriver
}
func (repository *ProductRepository) FindByID(ctx context.Context, id int) (*Product, error) {
const findSQL = `SELECT id, name FROM product WHERE id = ?`
row := repository.db.QueryRow(ctx, findSQL, id)
var product Product
err := row.Scan(&product.ID, &product.Name)
if errors.Is(err, sql.ErrNoRows) {
// Error from newNotFoundError will have a stack trace pointing to the line in which
// it was called.
return nil, newNotFoundError()
}
if err != nil {
// Use errors.Errorf to wrap the library error with the message context and
// error fields to be used for structured logging.
return nil, errors.Errorf(
"%w: %v", errSQLError, err.Error(),
errors.String("sql", findSQL),
errors.Int("productID", id),
)
}
return &product, nil
}
type ErrorJSON struct {
Error string `json:"error"`
StackTrace []StackTraceFrameJSON `json:"stackTrace"`
ProductID int `json:"productID"`
SQL string `json:"sql"`
}
type StackTraceFrameJSON struct {
Function string `json:"function"`
File string `json:"file"`
Line int `json:"line"`
}
func errToJSON(sourceError error) ErrorJSON {
jsonData, err := json.Marshal(sourceError)
if err != nil {
log.Fatal(err)
}
var jsonError ErrorJSON
err = json.Unmarshal(jsonData, &jsonError)
if err != nil {
log.Fatal(err)
}
return jsonError
}
func ExampleLog_typicalErrorHandling() {
repository := ProductRepository{db: &SQLDriver{}}
// Imitating no rows error.
repository.db.err = sql.ErrNoRows
_, notFoundError := repository.FindByID(context.Background(), 123)
if notFoundError != nil {
// Print error as a text.
fmt.Println("repository error:", notFoundError)
fmt.Println("repository error is ErrNotFound:", errors.Is(notFoundError, ErrNotFound))
// Marshal error into structured JSON.
jsonError := errToJSON(notFoundError)
fmt.Println(`repository error as JSON, field "error":`, jsonError.Error)
fmt.Println(`repository error as JSON, field "stackTrace[0].function":`, jsonError.StackTrace[0].Function)
fmt.Println(
`repository error as JSON, field "stackTrace[0].file":`,
jsonError.StackTrace[0].File[strings.LastIndex(jsonError.StackTrace[0].File, "/")+1:],
)
fmt.Println(`repository error as JSON, field "stackTrace[0].line":`, jsonError.StackTrace[0].Line)
// Log error with structured logger.
logger := errorstest.NewLogger()
errors.Log(notFoundError, logger)
fmt.Println(`log repository error, message:`, logger.Message)
fmt.Printf(
"log repository error, first line of stack trace: %s %s:%d\n",
logger.StackTrace[0].Name(),
logger.StackTrace[0].File()[strings.LastIndex(logger.StackTrace[0].File(), "/")+1:],
logger.StackTrace[0].Line(),
)
}
// Imitating driver error.
repository.db.err = sql.ErrConnDone
_, sqlError := repository.FindByID(context.Background(), 123)
if sqlError != nil {
// Print error as a text.
fmt.Println("repository error:", sqlError)
fmt.Println("repository error is errSQLError:", errors.Is(sqlError, errSQLError))
// Marshal error into structured JSON.
jsonError := errToJSON(sqlError)
fmt.Println(`repository error as JSON, field "error":`, jsonError.Error)
fmt.Println(`repository error as JSON, field "stackTrace[0].function":`, jsonError.StackTrace[0].Function)
fmt.Println(
`repository error as JSON, field "stackTrace[0].file":`,
jsonError.StackTrace[0].File[strings.LastIndex(jsonError.StackTrace[0].File, "/")+1:],
)
fmt.Println(`repository error as JSON, field "stackTrace[0].line":`, jsonError.StackTrace[0].Line)
// Log error with structured logger.
logger := errorstest.NewLogger()
errors.Log(sqlError, logger)
fmt.Println(`log repository error, message:`, logger.Message)
fmt.Println(`log repository error, fields:`, logger.Fields)
fmt.Printf(
"log repository error, first line of stack trace: %s %s:%d\n",
logger.StackTrace[0].Name(),
logger.StackTrace[0].File()[strings.LastIndex(logger.StackTrace[0].File(), "/")+1:],
logger.StackTrace[0].Line(),
)
}
// Output:
// repository error: not found
// repository error is ErrNotFound: true
// repository error as JSON, field "error": not found
// repository error as JSON, field "stackTrace[0].function": github.com/muonsoft/errors_test.(*ProductRepository).FindByID
// repository error as JSON, field "stackTrace[0].file": example_log_test.go
// repository error as JSON, field "stackTrace[0].line": 63
// log repository error, message: not found
// log repository error, first line of stack trace: github.com/muonsoft/errors_test.(*ProductRepository).FindByID example_log_test.go:63
// repository error: sql error: sql: connection is already closed
// repository error is errSQLError: true
// repository error as JSON, field "error": sql error: sql: connection is already closed
// repository error as JSON, field "stackTrace[0].function": github.com/muonsoft/errors_test.(*ProductRepository).FindByID
// repository error as JSON, field "stackTrace[0].file": example_log_test.go
// repository error as JSON, field "stackTrace[0].line": 68
// log repository error, message: sql error: sql: connection is already closed
// log repository error, fields: map[productID:123 sql:SELECT id, name FROM product WHERE id = ?]
// log repository error, first line of stack trace: github.com/muonsoft/errors_test.(*ProductRepository).FindByID example_log_test.go:68
}