From ec954b31305382fdb41d12fdd324a170204a5452 Mon Sep 17 00:00:00 2001 From: CC11001100 Date: Tue, 8 Apr 2025 17:28:39 +0800 Subject: [PATCH] fix: improve panic recovery in main function - Move panic recovery defer to the beginning of main function to ensure it can catch panics from all subsequent function calls - Remove unused setupErrorRecovery function - Add explanatory comment for the defer placement This change ensures proper error handling throughout the entire program execution, rather than just within the setupErrorRecovery function scope. --- cmd/cursor-id-modifier/main.go | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/cmd/cursor-id-modifier/main.go b/cmd/cursor-id-modifier/main.go index 89de5f3..4ff9e0e 100644 --- a/cmd/cursor-id-modifier/main.go +++ b/cmd/cursor-id-modifier/main.go @@ -11,13 +11,13 @@ import ( "runtime/debug" "strings" + "github.com/sirupsen/logrus" + "github.com/yuaotian/go-cursor-help/internal/config" "github.com/yuaotian/go-cursor-help/internal/lang" "github.com/yuaotian/go-cursor-help/internal/process" "github.com/yuaotian/go-cursor-help/internal/ui" "github.com/yuaotian/go-cursor-help/pkg/idgen" - - "github.com/sirupsen/logrus" ) // Global variables @@ -29,7 +29,15 @@ var ( ) func main() { - setupErrorRecovery() + // Place defer at the beginning of main to ensure it can catch panics from all subsequent function calls + defer func() { + if r := recover(); r != nil { + log.Errorf("Panic recovered: %v\n", r) + debug.PrintStack() + waitExit() + } + }() + handleFlags() setupLogger() @@ -73,16 +81,6 @@ func main() { } } -func setupErrorRecovery() { - defer func() { - if r := recover(); r != nil { - log.Errorf("Panic recovered: %v\n", r) - debug.PrintStack() - waitExit() - } - }() -} - func handleFlags() { flag.Parse() if *showVersion {