-
Notifications
You must be signed in to change notification settings - Fork 17
/
panic_go1_12.go
46 lines (38 loc) · 950 Bytes
/
panic_go1_12.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
// build go1.12
package emperror
import (
"fmt"
"emperror.dev/errors"
)
// Panic panics if the passed error is not nil.
// If the error does not contain any stack trace, the function attaches one, starting from the frame of the
// "Panic" function call.
//
// This function is useful with HandleRecover when panic is used as a flow control tool to stop the application.
func Panic(err error) {
if err != nil {
var st stackTracer
if !errors.As(err, &st) {
err = errors.WithStackDepth(err, 1)
}
panic(err)
}
}
// Recover accepts a recovered panic (if any) and converts it to an error (if necessary).
func Recover(r interface{}) (err error) {
if r != nil {
switch x := r.(type) {
case string:
err = errors.NewPlain(x)
case error:
err = x
default:
err = fmt.Errorf("unknown panic, received: %v", r)
}
var st stackTracer
if !errors.As(err, &st) {
err = errors.WithStackDepth(err, 3)
}
}
return err
}