2020-07-26 17:09:05 +08:00
|
|
|
package rescue
|
|
|
|
|
|
|
|
import (
|
2023-05-08 23:49:13 +08:00
|
|
|
"context"
|
2020-07-26 17:09:05 +08:00
|
|
|
"sync/atomic"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
2022-01-04 15:51:32 +08:00
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
2020-07-26 17:09:05 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
logx.Disable()
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestRescue(t *testing.T) {
|
|
|
|
var count int32
|
|
|
|
assert.NotPanics(t, func() {
|
|
|
|
defer Recover(func() {
|
|
|
|
atomic.AddInt32(&count, 2)
|
|
|
|
}, func() {
|
|
|
|
atomic.AddInt32(&count, 3)
|
|
|
|
})
|
|
|
|
|
|
|
|
panic("hello")
|
|
|
|
})
|
|
|
|
assert.Equal(t, int32(5), atomic.LoadInt32(&count))
|
|
|
|
}
|
2023-05-08 23:49:13 +08:00
|
|
|
|
|
|
|
func TestRescueCtx(t *testing.T) {
|
|
|
|
var count int32
|
|
|
|
assert.NotPanics(t, func() {
|
|
|
|
defer RecoverCtx(context.Background(), func() {
|
|
|
|
atomic.AddInt32(&count, 2)
|
|
|
|
}, func() {
|
|
|
|
atomic.AddInt32(&count, 3)
|
|
|
|
})
|
|
|
|
|
|
|
|
panic("hello")
|
|
|
|
})
|
|
|
|
assert.Equal(t, int32(5), atomic.LoadInt32(&count))
|
|
|
|
}
|