Home > Article > Backend Development > How to Handle Errors When Deferring Functions with Return Values in Go?
Handling Errors When Deferring Functions with Return Values
The golang/errcheck linter warns when deferring a function that returns a value without checking the error. To address this, one must store the return value, which requires deferring another function that calls the original one.
One approach is to use an anonymous function, as demonstrated below:
<code class="go">defer func() { if err := r.Body.Close(); err != nil { fmt.Println("Error when closing:", err) } }()</code>
Alternatively, a helper function can be defined:
<code class="go">func Check(f func() error) { if err := f(); err != nil { fmt.Println("Received error:", err) } }</code>
which can be used as follows:
<code class="go">defer Check(r.Body.Close)</code>
For multiple deferred function calls, a modified helper function accepting multiple functions can be created:
<code class="go">func Checks(fs ...func() error) { for i := len(fs) - 1; i >= 0; i-- { if err := fs[i](); err != nil { fmt.Println("Received error:", err) } } }</code>
Additionally, the Checks() function utilizes a downward loop to reflect the first-in-last-out execution order of deferred functions.
The above is the detailed content of How to Handle Errors When Deferring Functions with Return Values in Go?. For more information, please follow other related articles on the PHP Chinese website!