From 2f23941546dfec341763cd0946bdcc1f4196c47b Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Thu, 3 Aug 2023 14:16:29 +0000 Subject: [PATCH] server/email: simplify and cleanup - Only print the error once - Remove unnecessary var - Use debug.Stack instead of hand-rolled logic - Ignore json.Marshal errors in a simpler way --- server/email.go | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/server/email.go b/server/email.go index a6933bfbfa3a38a66edf403d628c3bdd5b39661b..4cfa37be6396f7c7ed2a88db0cebc8d28dc1848e 100644 --- a/server/email.go +++ b/server/email.go @@ -8,7 +8,7 @@ import ( "io" "log" gomail "net/mail" - "runtime" + "runtime/debug" "strings" "github.com/99designs/gqlgen/graphql" @@ -22,16 +22,14 @@ import ( // Provides a graphql.RecoverFunc which will print the stack trace, and if // debug mode is not enabled, email it to the administrator. func EmailRecover(ctx context.Context, _origErr interface{}) error { - log.Println(_origErr) - var ( - ok bool - origErr error - ) - if origErr, ok = _origErr.(error); !ok { + origErr, ok := _origErr.(error) + if !ok { log.Printf("Unexpected error in recover: %v\n", origErr) return fmt.Errorf("internal system error") } + log.Println(origErr) + if errors.Is(origErr, context.Canceled) { return origErr } @@ -44,10 +42,8 @@ func EmailRecover(ctx context.Context, _origErr interface{}) error { return origErr } - stack := make([]byte, 32768) // 32 KiB - i := runtime.Stack(stack, false) - log.Println(origErr.Error()) - log.Println(string(stack[:i])) + stack := string(debug.Stack()) + log.Println(stack) if config.Debug { return fmt.Errorf("internal system error") } @@ -74,15 +70,12 @@ func EmailRecover(ctx context.Context, _origErr interface{}) error { if err := recover(); err != nil { reader = strings.NewReader(fmt.Sprintf(`An error occured outside of the GraphQL context: - %s`, string(stack[:i]))) + %s`, stack)) } }() quser := auth.ForContext(ctx) octx := graphql.GetOperationContext(ctx) - vars, err := json.Marshal(octx.Variables) - if err != nil { - vars = []byte{}[:] - } + vars, _ := json.Marshal(octx.Variables) reader = strings.NewReader( fmt.Sprintf(`Error occured processing GraphQL request: @@ -99,7 +92,7 @@ With these variables: The following stack trace was produced: %s`, origErr, quser.Username, quser.Email, octx.RawQuery, - string(vars), string(stack[:i]))) + string(vars), stack)) }() email.EnqueueStd(ctx, header, reader, nil)