aboutsummaryrefslogtreecommitdiffhomepage
path: root/common
diff options
context:
space:
mode:
authorBjørn Erik Pedersen <[email protected]>2024-02-01 16:35:41 +0100
committerBjørn Erik Pedersen <[email protected]>2024-02-01 19:53:51 +0100
commit8d42a7942ad2cc3ecff2ad90502c7e9e87da5d52 (patch)
treed5c91d1e063eb60138084b80d22073fe5a89e750 /common
parent4174a7866b75c6ae10827cc77dbae0676af8e5eb (diff)
downloadhugo-8d42a7942ad2cc3ecff2ad90502c7e9e87da5d52.tar.gz
hugo-8d42a7942ad2cc3ecff2ad90502c7e9e87da5d52.zip
Improve nilpointer error message
Diffstat (limited to 'common')
-rw-r--r--common/herrors/errors.go21
1 files changed, 21 insertions, 0 deletions
diff --git a/common/herrors/errors.go b/common/herrors/errors.go
index 59739a86a..7c389c1ae 100644
--- a/common/herrors/errors.go
+++ b/common/herrors/errors.go
@@ -19,8 +19,10 @@ import (
"fmt"
"io"
"os"
+ "regexp"
"runtime"
"runtime/debug"
+ "strings"
"time"
)
@@ -116,3 +118,22 @@ func IsNotExist(err error) bool {
return false
}
+
+var nilPointerErrRe = regexp.MustCompile(`at <(.*)>: error calling (.*?): runtime error: invalid memory address or nil pointer dereference`)
+
+func ImproveIfNilPointer(inErr error) (outErr error) {
+ outErr = inErr
+
+ m := nilPointerErrRe.FindStringSubmatch(inErr.Error())
+ if len(m) == 0 {
+ return
+ }
+ call := m[1]
+ field := m[2]
+ parts := strings.Split(call, ".")
+ receiverName := parts[len(parts)-2]
+ receiver := strings.Join(parts[:len(parts)-1], ".")
+ s := fmt.Sprintf("– %s is nil; wrap it in if or with: {{ with %s }}{{ .%s }}{{ end }}", receiverName, receiver, field)
+ outErr = errors.New(nilPointerErrRe.ReplaceAllString(inErr.Error(), s))
+ return
+}