File tree Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Expand file tree Collapse file tree 2 files changed +26
-1
lines changed Original file line number Diff line number Diff line change @@ -4,9 +4,15 @@ import (
44 "fmt"
55)
66
7+ // OnGuard is a global hook for Guard
8+ var OnGuard func (r any )
9+
710// Guard recover from panic and set err
811func Guard (err * error ) {
912 if r := recover (); r != nil {
13+ if fn := OnGuard ; fn != nil {
14+ fn (r )
15+ }
1016 if re , ok := r .(error ); ok {
1117 * err = re
1218 } else {
Original file line number Diff line number Diff line change @@ -2,8 +2,9 @@ package rg
22
33import (
44 "errors"
5- "github.com/stretchr/testify/require"
65 "testing"
6+
7+ "github.com/stretchr/testify/require"
78)
89
910func TestGuard (t * testing.T ) {
@@ -16,6 +17,24 @@ func TestGuard(t *testing.T) {
1617 require .Equal (t , "hello" , err .Error ())
1718}
1819
20+ func TestOnGuard (t * testing.T ) {
21+ var err error
22+ var err2 any
23+ OnGuard = func (e any ) {
24+ err2 = e
25+ }
26+ defer func () {
27+ OnGuard = nil
28+ }()
29+ func () {
30+ defer Guard (& err )
31+ panic (errors .New ("hello" ))
32+ }()
33+ require .Error (t , err )
34+ require .Equal (t , err , err2 )
35+ require .Equal (t , "hello" , err .Error ())
36+ }
37+
1938func TestGuardNotError (t * testing.T ) {
2039 var err error
2140 func () {
You can’t perform that action at this time.
0 commit comments