Skip to content

Commit

Permalink
APIGOV-27289 - more informative NPE (#751)
Browse files Browse the repository at this point in the history
* APIGOV-27289 - more informative NPE

* fix tests
  • Loading branch information
dgghinea authored Apr 2, 2024
1 parent 6b2446f commit 4dad2e3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
15 changes: 13 additions & 2 deletions pkg/util/exception/exception.go
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -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)
}
}
}()
}
Expand Down
21 changes: 21 additions & 0 deletions pkg/util/exception/exeception_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package exception

import (
"errors"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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)
}

0 comments on commit 4dad2e3

Please sign in to comment.