init: 1.0.0
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
package rescue
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/perfect-panel/ppanel-server/pkg/logger"
|
||||
)
|
||||
|
||||
// Recover is used with defer to do cleanup on panics.
|
||||
// Use it like:
|
||||
//
|
||||
// defer Recover(func() {})
|
||||
func Recover(cleanups ...func()) {
|
||||
for _, cleanup := range cleanups {
|
||||
cleanup()
|
||||
}
|
||||
|
||||
if p := recover(); p != nil {
|
||||
log.Print(p)
|
||||
}
|
||||
}
|
||||
|
||||
// RecoverCtx is used with defer to do cleanup on panics.
|
||||
func RecoverCtx(ctx context.Context, cleanups ...func()) {
|
||||
for _, cleanup := range cleanups {
|
||||
cleanup()
|
||||
}
|
||||
|
||||
if p := recover(); p != nil {
|
||||
logger.WithContext(ctx).Errorf("%+v\n%s", p, debug.Stack())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package rescue
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func init() {
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
Reference in New Issue
Block a user