-
Notifications
You must be signed in to change notification settings - Fork 11
/
error.go
462 lines (408 loc) · 9.49 KB
/
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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
Copyright 2017-present Wenhui Shen <www.webx.top>
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 echo
import (
"errors"
"fmt"
"html"
"html/template"
"net/http"
"os"
"runtime"
"strconv"
"strings"
pkgCode "github.com/webx-top/echo/code"
)
const (
SnippetLineNumbers = 13
StackSize = 4 << 10 // 4 KB
)
// ==========================================
// Error
// ==========================================
func NewError(msg string, code ...pkgCode.Code) *Error {
return NewErrorWith(nil, msg, code...)
}
func NewErrorWith(err error, msg string, code ...pkgCode.Code) *Error {
e := &Error{Code: pkgCode.Failure, Message: msg, Extra: H{}, cause: err}
if len(code) > 0 {
e.Code = code[0]
}
if len(msg) == 0 {
if err != nil {
e.Message = err.Error()
} else {
e.Message = e.Code.String()
}
}
return e
}
func IsErrorCode(err error, code pkgCode.Code) bool {
val, ok := err.(*Error)
if !ok && !errors.As(err, &val) {
return false
}
return val.Code.Is(code)
}
func InErrorCode(err error, codes ...pkgCode.Code) bool {
val, ok := err.(*Error)
if !ok && !errors.As(err, &val) {
return false
}
return val.Code.In(codes...)
}
type Error struct {
Code pkgCode.Code
Message string
Zone string
Extra H
cause error
cloned bool
}
// Error returns message.
func (e *Error) Error() string {
return e.Message
}
func (e *Error) NoClone() *Error {
e.cloned = true
return e
}
func (e *Error) Clone() *Error {
var extra H
if e.Extra != nil {
extra = e.Extra.Clone()
}
return &Error{
Code: e.Code,
Message: e.Message,
Zone: e.Zone,
Extra: extra,
cause: e.cause,
cloned: true,
}
}
func (e *Error) Set(key string, value interface{}) *Error {
if !e.cloned {
e2 := e.Clone()
e2.Extra.Set(key, value)
return e2
}
e.Extra.Set(key, value)
return e
}
func (e *Error) SetMessage(message string) *Error {
if !e.cloned {
e2 := e.Clone()
e2.Message = message
return e2
}
e.Message = message
return e
}
func (e *Error) SetZone(zone string) *Error {
if !e.cloned {
e2 := e.Clone()
e2.Zone = zone
return e2
}
e.Zone = zone
return e
}
func (e *Error) SetError(err error) *Error {
if !e.cloned {
e2 := e.Clone()
e2.cause = err
return e2
}
e.cause = err
return e
}
func (e *Error) Delete(keys ...string) *Error {
if !e.cloned {
e2 := e.Clone()
e2.Extra.Delete(keys...)
return e2
}
e.Extra.Delete(keys...)
return e
}
func (e *Error) ErrorCode() int {
return e.Code.Int()
}
func (e *Error) Cause() error {
return e.cause
}
func (e *Error) Unwrap() error {
return e.cause
}
// ==========================================
// HTTPError
// ==========================================
func NewHTTPError(code int, msg ...string) *HTTPError {
he := &HTTPError{Code: code, Message: http.StatusText(code)}
if len(msg) > 0 {
he.Message = msg[0]
}
return he
}
type HTTPError struct {
Code int
Message string
raw error
}
// Error returns message.
func (e *HTTPError) Error() string {
if e.raw != nil {
return e.Message + `: ` + e.raw.Error()
}
return e.Message
}
// SetRaw sets the raw error
func (e *HTTPError) SetRaw(err error) *HTTPError {
e.raw = err
return e
}
// Raw gets the raw error
func (e *HTTPError) Raw() error {
return e.raw
}
func (e *HTTPError) Unwrap() error {
return e.raw
}
// ==========================================
// PanicError
// ==========================================
func NewPanicError(recovered interface{}, err error, debugAndDisableStackAll ...bool) *PanicError {
var debug, disableStackAll bool
switch len(debugAndDisableStackAll) {
case 2:
disableStackAll = debugAndDisableStackAll[1]
fallthrough
case 1:
debug = debugAndDisableStackAll[0]
}
return &PanicError{
error: err,
Raw: recovered,
Traces: make([]*Trace, 0),
Snippets: make([]*SnippetGroup, 0),
debug: debug,
disableStackAll: disableStackAll,
}
}
type PanicError struct {
error
Raw interface{}
Traces []*Trace
Snippets []*SnippetGroup
debug bool
disableStackAll bool
}
type SnippetGroup struct {
Path string
Index int
Snippet []*Snippet
}
func (sg *SnippetGroup) String() string {
var s string
var l int
for _, snippet := range sg.Snippet {
ns := strconv.Itoa(snippet.Number)
if l == 0 {
l = len(ns) + 5
}
if snippet.Current {
ns = "[" + ns + "]"
} else {
ns = " " + ns
}
s += fmt.Sprintf("\n\t%*s%v", -l, ns, snippet.Code)
}
return s
}
func (sg *SnippetGroup) TableRow() string {
var s string
for _, snippet := range sg.Snippet {
ns := strconv.Itoa(snippet.Number)
cd := snippet.Code
cd = html.EscapeString(cd)
cd = strings.Replace(cd, "\t", " ", -1)
cd = strings.Replace(cd, " ", " ", -1)
if snippet.Current {
ns = "<strong>" + ns + "</strong>"
cd = "<strong>" + cd + "</strong>"
}
s += "<tr><td class='left'>" + ns + "</td><td class='right'>" + cd + "</td></tr>"
}
return s
}
type Snippet struct {
Number int
Code string
Current bool
}
type Trace struct {
Line int
File string
Func string
HasErr bool
}
func (p *PanicError) JSONString() string {
return Dump(p, false)
}
func (p *PanicError) Error() string {
return p.String()
}
func (p *PanicError) String() string {
if len(p.Snippets) == 0 {
return p.error.Error()
}
e := p.error.Error()
for _, sg := range p.Snippets {
f := sg.Path + ":" + strconv.Itoa(p.Traces[sg.Index].Line)
if pos := strings.Index(e, f); pos > -1 {
start := pos + len(f) + 1
var s string
if start < len(e) {
s = e[start:]
}
e = e[0:pos+len(f)] + "\n" + sg.String() + "\n\n" + s
}
}
return e
}
func (p *PanicError) HTML() template.HTML {
if len(p.Snippets) == 0 {
return template.HTML(`<pre>` + p.error.Error() + `</pre>`)
}
table := "<style>.panic-table-snippet td.left{width:100px;text-align:right}.panic-table-trace td.left{width:50%}</style>"
for _, sg := range p.Snippets {
table += `<table class="table table-bordered panic-table panic-table-snippet">`
table += `<thead><tr><th colspan="2">` + sg.Path + `</th></tr></thead>`
table += `<tbody>`
table += sg.TableRow()
table += `</tbody>`
table += `</table>`
}
table += `<table class="table table-bordered panic-table panic-table-trace">`
table += `<thead><tr><th colspan="2">Trace</th></tr><tr><th>File</th><th>Func</th></tr></thead>`
table += `<tbody>`
for _, ts := range p.Traces {
f := html.EscapeString(ts.File) + `:` + strconv.Itoa(ts.Line)
table += `<tr><td class='left'>`
if ts.HasErr {
table += `<strong>` + f + `</strong>`
table += `</td><td class='right'><strong>` + ts.Func + `</strong>`
} else {
table += f + `</td><td class='right'>` + ts.Func
}
table += `</td></tr>`
}
table += `</tbody>`
table += `</table>`
return template.HTML(table)
}
func (p *PanicError) AddTrace(trace *Trace, content ...string) *PanicError {
if len(p.Snippets) == 0 {
if !trace.HasErr && strings.Contains(trace.File, workDir) {
trace.HasErr = true
}
if trace.HasErr {
index := len(p.Traces)
if len(content) > 0 {
p.ExtractSnippets(content[0], trace.File, trace.Line, index)
} else {
p.ExtractFileSnippets(trace.File, trace.Line, index)
}
}
}
p.Traces = append(p.Traces, trace)
return p
}
func (p *PanicError) ExtractFileSnippets(file string, curLineNum int, index int) error {
content, err := os.ReadFile(file)
if err != nil {
return err
}
return p.ExtractSnippets(string(content), file, curLineNum, index)
}
func (p *PanicError) ExtractSnippets(content string, file string, curLineNum int, index int) error {
half := SnippetLineNumbers / 2
lines := strings.Split(string(content), "\n")
group := &SnippetGroup{
Path: file,
Index: index,
Snippet: []*Snippet{},
}
for lineNum := curLineNum - half; lineNum <= curLineNum+half; lineNum++ {
if len(lines) >= lineNum && lineNum > 0 {
group.Snippet = append(group.Snippet, &Snippet{
Number: lineNum,
Code: lines[lineNum-1],
Current: lineNum == curLineNum,
})
}
}
if len(group.Snippet) > 0 {
p.Snippets = append(p.Snippets, group)
}
return nil
}
func (p *PanicError) SetError(err error) *PanicError {
p.error = err
return p
}
func (p *PanicError) SetErrorString(errStr string) *PanicError {
p.error = errors.New(errStr)
return p
}
func (p *PanicError) SetDebug(on bool) *PanicError {
p.debug = on
return p
}
func (p *PanicError) Debug() bool {
return p.debug
}
func (p *PanicError) Parse(stackSizes ...int) *PanicError {
stackSize := StackSize
if len(stackSizes) > 0 {
stackSize = stackSizes[0]
}
var err error
switch r := p.Raw.(type) {
case error:
err = r
default:
err = fmt.Errorf("%v", r)
}
if p.disableStackAll {
p.SetError(err)
return p
}
content := "[PANIC RECOVER] " + err.Error()
for i := 2; len(content) < stackSize; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
t := &Trace{
File: file,
Line: line,
Func: runtime.FuncForPC(pc).Name(),
}
p.AddTrace(t)
content += "\n" + fmt.Sprintf(`%v:%v`, file, line)
}
p.SetErrorString(content)
return p
}