From 898d23d733621ea8908c9a4f496f675243b9e154 Mon Sep 17 00:00:00 2001 From: spiral Date: Wed, 23 Nov 2022 05:17:56 +0000 Subject: [PATCH] fix(stats): fix crash when messages task fails, add Sentry integration --- services/scheduled_tasks/main.go | 32 ++++++++++++++++++++++++++++++- services/scheduled_tasks/tasks.go | 11 ----------- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/services/scheduled_tasks/main.go b/services/scheduled_tasks/main.go index 9550508a..3521a9e2 100644 --- a/services/scheduled_tasks/main.go +++ b/services/scheduled_tasks/main.go @@ -4,10 +4,21 @@ import ( "fmt" "log" "os" + "runtime/debug" + "strings" "time" + + "github.com/getsentry/sentry-go" ) func main() { + err := sentry.Init(sentry.ClientOptions{ + Dsn: os.Getenv("SENTRY_DSN"), + }) + if err != nil { + panic(err) + } + log.Println("connecting to databases") connect_dbs() @@ -41,7 +52,26 @@ func withtime(name string, todo func()) func() { func doforever(dur time.Duration, todo func()) { for { - go todo() + go wrapRecover(todo) time.Sleep(dur) } } + +func wrapRecover(todo func()) { + defer func() { + if err := recover(); err != nil { + if val, ok := err.(error); ok { + sentry.CaptureException(val) + } else { + sentry.CaptureMessage(fmt.Sprint("unknown error", err)) + } + + stack := strings.Split(string(debug.Stack()), "\n") + stack = stack[7:] + log.Println("error running tasks:", err.(error).Error()) + fmt.Println(strings.Join(stack, "\n")) + } + }() + + todo() +} diff --git a/services/scheduled_tasks/tasks.go b/services/scheduled_tasks/tasks.go index 0af00a99..6ea87225 100644 --- a/services/scheduled_tasks/tasks.go +++ b/services/scheduled_tasks/tasks.go @@ -4,20 +4,9 @@ import ( "context" "fmt" "log" - "runtime/debug" - "strings" ) func task_main() { - defer func() { - if err := recover(); err != nil { - stack := strings.Split(string(debug.Stack()), "\n") - stack = stack[7:] - log.Println("error running tasks:", err.(error).Error()) - fmt.Println(strings.Join(stack, "\n")) - } - }() - log.Println("running per-minute scheduled tasks") update_db_meta()