From febcadb42ce53a9cb372b15c2bf67721fe448c64 Mon Sep 17 00:00:00 2001 From: CaIon <1808837298@qq.com> Date: Fri, 12 Jan 2024 13:49:53 +0800 Subject: [PATCH] chore: add SafeGoroutine --- common/go-channel.go | 16 ++++++++++++++++ model/log.go | 4 +++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/common/go-channel.go b/common/go-channel.go index 73c5f51..4f00dff 100644 --- a/common/go-channel.go +++ b/common/go-channel.go @@ -1,5 +1,21 @@ package common +import ( + "fmt" + "runtime/debug" +) + +func SafeGoroutine(f func()) { + go func() { + defer func() { + if r := recover(); r != nil { + SysError(fmt.Sprintf("child goroutine panic occured: error: %v, stack: %s", r, string(debug.Stack()))) + } + }() + f() + }() +} + func SafeSend(ch chan bool, value bool) (closed bool) { defer func() { // Recover from panic if one occured. A panic would mean the channel was closed. diff --git a/model/log.go b/model/log.go index f96191f..b4d1188 100644 --- a/model/log.go +++ b/model/log.go @@ -80,7 +80,9 @@ func RecordConsumeLog(ctx context.Context, userId int, channelId int, promptToke common.LogError(ctx, "failed to record log: "+err.Error()) } if common.DataExportEnabled { - go LogQuotaData(userId, username, modelName, quota, common.GetTimestamp()) + common.SafeGoroutine(func() { + LogQuotaData(userId, username, modelName, quota, common.GetTimestamp()) + }) } }