Skip to content

Commit 96135ea

Browse files
committed
feat: add OnGuard
1 parent f4bb40a commit 96135ea

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

guard.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff 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
811
func 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 {

guard_test.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ package rg
22

33
import (
44
"errors"
5-
"github.com/stretchr/testify/require"
65
"testing"
6+
7+
"github.com/stretchr/testify/require"
78
)
89

910
func 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+
1938
func TestGuardNotError(t *testing.T) {
2039
var err error
2140
func() {

0 commit comments

Comments
 (0)