Files
aggregate_translate_server/utils/utility/safego.go
hucan 9a954cedc0
Some checks failed
Build / build (push) Has been cancelled
CodeQL / Analyze (go) (push) Has been cancelled
build / Build (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitee (push) Has been cancelled
GitHub Actions Mirror / mirror_to_gitlab (push) Has been cancelled
Issue Close Require / issue-close-require (push) Has been cancelled
Issue Check Inactive / issue-check-inactive (push) Has been cancelled
1、
2025-08-28 11:43:11 +08:00

45 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utility
import (
"fmt"
"runtime"
"runtime/debug"
"strings"
"github.com/go-admin-team/go-admin-core/logger"
)
// SafeGo 安全地启动一个 goroutine捕获 panic
func SafeGo(fn func()) {
go func() {
defer func() {
if r := recover(); r != nil {
// 记录 Goroutine ID、panic 信息和堆栈
logger.Error(fmt.Sprintf("Recovered from panic in Goroutine %s: %v\nStack Trace:\n%s", GetGoroutineID(), r, string(debug.Stack())))
}
}()
fn()
}()
}
// 获取 Goroutine ID
func GetGoroutineID() string {
buf := make([]byte, 64)
n := runtime.Stack(buf, false)
stack := string(buf[:n])
// 提取 Goroutine ID
id := strings.Split(stack, " ")[1]
return id
}
func SafeGoParam[T any](fn func(T), param T) {
go func() {
defer func() {
if r := recover(); r != nil {
logger.Error(fmt.Sprintf(" SafeGoParam Recovered from panic in Goroutine %s: %v\nStack Trace:\n%s", GetGoroutineID(), r, string(debug.Stack())))
}
}()
fn(param) // 执行传入的函数
}()
}