From 4dad2e31be78b1a84287dbe507ca703b40cfa35a Mon Sep 17 00:00:00 2001 From: Dragos Gabriel Ghinea <142506926+dgghinea@users.noreply.github.com> Date: Tue, 2 Apr 2024 19:59:25 +0300 Subject: [PATCH] APIGOV-27289 - more informative NPE (#751) * APIGOV-27289 - more informative NPE * fix tests --- pkg/util/exception/exception.go | 15 +++++++++++++-- pkg/util/exception/exeception_test.go | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/pkg/util/exception/exception.go b/pkg/util/exception/exception.go index b3c314c20..1a47d56cc 100644 --- a/pkg/util/exception/exception.go +++ b/pkg/util/exception/exception.go @@ -1,5 +1,11 @@ package exception +import ( + "fmt" + "runtime/debug" + "strings" +) + // Block - defines the try, catch and finally code blocks type Block struct { Try func() @@ -28,8 +34,13 @@ func (block Block) Do() { if block.Catch != nil { defer func() { - if r := recover(); r != nil { - block.Catch(r.(error)) + if obj := recover(); obj != nil { + err := obj.(error) + if strings.Contains(err.Error(), "nil pointer dereference") { + block.Catch(fmt.Errorf(err.Error() + ": \n " + string(debug.Stack()))) + } else { + block.Catch(err) + } } }() } diff --git a/pkg/util/exception/exeception_test.go b/pkg/util/exception/exeception_test.go index dc24a33ad..11ea08219 100644 --- a/pkg/util/exception/exeception_test.go +++ b/pkg/util/exception/exeception_test.go @@ -2,6 +2,7 @@ package exception import ( "errors" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -58,3 +59,23 @@ func TestExceptionTryCatchFinallyBlock(t *testing.T) { assert.Equal(t, "try_catch_finally_err", catchErr.Error()) assert.Equal(t, "trycatchfinally", executionOrder) } + +func TestExceptionTryCatchBlockWithNPE(t *testing.T) { + var catchErr error + var executionOrder string + tryCatchFinallyBlockException := Block{ + Try: func() { + executionOrder = "try" + b := Block{} + b.Try() + }, + Catch: func(err error) { + executionOrder = executionOrder + "catch" + catchErr = err + }, + }.Do + + assert.NotPanics(t, tryCatchFinallyBlockException) + assert.NotNil(t, catchErr) + assert.Equal(t, strings.Contains(catchErr.Error(), "runtime error: invalid memory address or nil pointer dereference"), true) +}