Debian Codegraph @

common/herrors/errors.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package herrors contains common Hugo errors and error related utilities.
15 package herrors
16
17 import (
18 "errors"
19 "fmt"
20 "os"
21 "regexp"
22 "runtime"
23 "strings"
24 "time"
25 )
26
27 // ErrorSender is a, typically, non-blocking error handler.
28 type ErrorSender interface {
29 SendError(err error)
30 }
31
32 // Recover is a helper function that can be used to capture panics.
33 // Put this at the top of a method/function that crashes in a template:
34 //
35 // defer herrors.Recover()
36 func Recover(args ...any) {
37 if r := recover(); r != nil {
38 fmt.Println("ERR:", r)
39 buf := make([]byte, 64<<10)
40 buf = buf[:runtime.Stack(buf, false)]
41 args = append(args, "stacktrace from panic: \n"+string(buf), "\n")
42 fmt.Println(args...)
43 }
44 }
45
46 // IsTimeoutError returns true if the given error is or contains a TimeoutError.
47 func IsTimeoutError(err error) bool {
48 return errors.Is(err, &TimeoutError{})
49 }
50
51 type TimeoutError struct {
52 Duration time.Duration
53 }
54
55 func (e *TimeoutError) Error() string {
56 return fmt.Sprintf("timeout after %s", e.Duration)
57 }
58
59 func (e *TimeoutError) Is(target error) bool {
60 _, ok := target.(*TimeoutError)
61 return ok
62 }
63
64 // errMessage wraps an error with a message.
65 type errMessage struct {
66 msg string
67 err error
68 }
69
70 func (e *errMessage) Error() string {
71 return e.msg
72 }
73
74 func (e *errMessage) Unwrap() error {
75 return e.err
76 }
77
78 // IsFeatureNotAvailableError returns true if the given error is or contains a FeatureNotAvailableError.
79 func IsFeatureNotAvailableError(err error) bool {
80 return errors.Is(err, &FeatureNotAvailableError{})
81 }
82
83 // ErrFeatureNotAvailable denotes that a feature is unavailable.
84 //
85 // We will, at least to begin with, make some Hugo features (SCSS with libsass) optional,
86 // and this error is used to signal those situations.
87 var ErrFeatureNotAvailable = &FeatureNotAvailableError{Cause: errors.New("this feature is not available in your current Hugo version, see https://goo.gl/YMrWcn for more information")}
88
89 // FeatureNotAvailableError is an error type used to signal that a feature is not available.
90 type FeatureNotAvailableError struct {
91 Cause error
92 }
93
94 func (e *FeatureNotAvailableError) Unwrap() error {
95 return e.Cause
96 }
97
98 func (e *FeatureNotAvailableError) Error() string {
99 return e.Cause.Error()
100 }
101
102 func (e *FeatureNotAvailableError) Is(target error) bool {
103 _, ok := target.(*FeatureNotAvailableError)
104 return ok
105 }
106
107 // Must panics if err != nil.
108 func Must(err error) {
109 if err != nil {
110 panic(err)
111 }
112 }
113
114 // IsNotExist returns true if the error is a file not found error.
115 // Unlike os.IsNotExist, this also considers wrapped errors.
116 func IsNotExist(err error) bool {
117 if os.IsNotExist(err) {
118 return true
119 }
120
121 // os.IsNotExist does not consider wrapped errors.
122 if os.IsNotExist(errors.Unwrap(err)) {
123 return true
124 }
125
126 return false
127 }
128
129 // IsExist returns true if the error is a file exists error.
130 // Unlike os.IsExist, this also considers wrapped errors.
131 func IsExist(err error) bool {
132 if os.IsExist(err) {
133 return true
134 }
135
136 // os.IsExist does not consider wrapped errors.
137 if os.IsExist(errors.Unwrap(err)) {
138 return true
139 }
140
141 return false
142 }
143
144 var nilPointerErrRe = regexp.MustCompile(`at <(.*)>: error calling (.*?): runtime error: invalid memory address or nil pointer dereference`)
145
146 const deferredPrefix = "__hdeferred/"
147
148 var deferredStringToRemove = regexp.MustCompile(`executing "__hdeferred/.*?" `)
149
150 // ImproveRenderErr improves the error message for rendering errors.
151 func ImproveRenderErr(inErr error) (outErr error) {
152 outErr = inErr
153 msg := improveIfNilPointerMsg(inErr)
154 if msg != "" {
155 outErr = &errMessage{msg: msg, err: outErr}
156 }
157
158 if strings.Contains(inErr.Error(), deferredPrefix) {
159 msg := deferredStringToRemove.ReplaceAllString(inErr.Error(), "executing ")
160 outErr = &errMessage{msg: msg, err: outErr}
161 }
162 return
163 }
164
165 func improveIfNilPointerMsg(inErr error) string {
166 m := nilPointerErrRe.FindStringSubmatch(inErr.Error())
167 if len(m) == 0 {
168 return ""
169 }
170 call := m[1]
171 field := m[2]
172 parts := strings.Split(call, ".")
173 if len(parts) < 2 {
174 return ""
175 }
176 receiverName := parts[len(parts)-2]
177 receiver := strings.Join(parts[:len(parts)-1], ".")
178 s := fmt.Sprintf("– %s is nil; wrap it in if or with: {{ with %s }}{{ .%s }}{{ end }}", receiverName, receiver, field)
179 return nilPointerErrRe.ReplaceAllString(inErr.Error(), s)
180 }
181
182 // Or returns the first non-nil error from the given list of errors.
183 // If all errors are nil, it returns nil.
184 func Or(errs ...error) error {
185 for _, err := range errs {
186 if err != nil {
187 return err
188 }
189 }
190 return nil
191 }