I want to test how certain code handles errors.
I want a function to return an error.
I have tried typing return 0/0
but then my application won't build
How can I force return an error?
Errors can be returned as nil , and in fact, it's the default, or “zero”, value of on error in Go. This is important since checking if err != nil is the idiomatic way to determine if an error was encountered (replacing the try / catch statements you may be familiar with in other programming languages).
You can create wrapped errors by using the %w flag with the fmt. Errorf function as shown in the following example. As you can see the application prints both the new error created using fmt. Errorf as well as the old error message that was passed to the %w flag.
Syntax for wrapping an error in Golang First we need to create a new error using errors. New() followed by fmt. Errorf() with the %w verb to wrap the error.
You can use the errors
package.
import "errors"
// [ ... ]
func failFunc() error {
return errors.New("Error message")
}
Here's the godoc: https://godoc.org/errors
you can return errors like this:
func ReturnError() (string, error){
return "", fmt.Errorf("this is an %s error", "internal server")
// or
return "", errors.New("this is an error")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With