2020-07-26 17:09:05 +08:00
|
|
|
package rescue
|
|
|
|
|
2023-05-08 23:08:31 +08:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"runtime/debug"
|
|
|
|
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
|
|
)
|
2020-07-26 17:09:05 +08:00
|
|
|
|
2021-02-22 16:47:02 +08:00
|
|
|
// Recover is used with defer to do cleanup on panics.
|
|
|
|
// Use it like:
|
2022-12-11 00:41:50 +08:00
|
|
|
//
|
|
|
|
// defer Recover(func() {})
|
2020-07-26 17:09:05 +08:00
|
|
|
func Recover(cleanups ...func()) {
|
|
|
|
for _, cleanup := range cleanups {
|
|
|
|
cleanup()
|
|
|
|
}
|
|
|
|
|
|
|
|
if p := recover(); p != nil {
|
|
|
|
logx.ErrorStack(p)
|
|
|
|
}
|
|
|
|
}
|
2023-05-08 23:08:31 +08:00
|
|
|
|
2023-05-08 23:49:13 +08:00
|
|
|
// RecoverCtx is used with defer to do cleanup on panics.
|
2023-05-08 23:08:31 +08:00
|
|
|
func RecoverCtx(ctx context.Context, cleanups ...func()) {
|
|
|
|
for _, cleanup := range cleanups {
|
|
|
|
cleanup()
|
|
|
|
}
|
|
|
|
|
|
|
|
if p := recover(); p != nil {
|
2023-05-08 23:49:13 +08:00
|
|
|
logx.WithContext(ctx).Errorf("%+v\n%s", p, debug.Stack())
|
2023-05-08 23:08:31 +08:00
|
|
|
}
|
|
|
|
}
|