-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpanic.go
More file actions
39 lines (35 loc) · 1.08 KB
/
panic.go
File metadata and controls
39 lines (35 loc) · 1.08 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
package errutil
import (
"runtime"
"errors"
)
// OnExpectedPanic recovers from an expected panic and provides expected error to the provided callback
// if panic is NOT an error interface it will be ra-raised
// example:
// defer OnExpected(func(err error){ doSomethingWithError(err) })
//
// note: this should be used sparingly; public APIs should NOT expect consumers to handle panics
func OnExpectedPanic(fn func(err error)) {
r := recover()
var runtimeErr runtime.Error
if err, ok := r.(error); ok && !errors.As(err, &runtimeErr) {
fn(err)
} else if r != nil {
panic(r)
}
}
// ExpectedPanicAsError sets the error pointer with the expected panic
// if panic is NOT an error interface it will be ra-raised
// note: this function must be deferred e.g.
// defer ExpectedPanicAsErr(&myErr)
//
// note: this should be used sparingly; public APIs should NOT expect consumers to handle panics
func ExpectedPanicAsError(errPtr *error) {
r := recover()
var runtimeErr runtime.Error
if err, ok := r.(error); ok && !errors.As(err, &runtimeErr) {
*errPtr = err
} else if r != nil {
panic(r)
}
}