To create and use error constants in Go, you can follow these steps:
errors
.package errors
errors
package, for example, constants.go
.package errors
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrInvalid = errors.New("invalid data")
ErrForbidden = errors.New("forbidden")
)
In this example, we define three error constants: ErrNotFound
, ErrInvalid
, and ErrForbidden
. Each constant is set to a new instance of the error
type with an appropriate error message.
package main
import (
"fmt"
"github.com/your-username/your-package/errors"
)
func main() {
// Example usage 1
if err != nil {
fmt.Println(errors.ErrNotFound)
}
// Example usage 2
if err != nil {
if errors.Is(err, errors.ErrForbidden) {
fmt.Println("This is a forbidden error.")
}
}
}
In the first example usage, we're printing the error constant errors.ErrNotFound
directly when the error occurs.
In the second example usage, we're checking if the error is equivalent to errors.ErrForbidden
using the errors.Is()
function from the errors
package. If it is, we print a specific message.
Note that the errors.Is(err, target)
function checks if the error err
is equal to or implements target
. This is especially useful when dealing with error wrapping.
That's it! These steps allow you to create and use error constants in Go to define common error types.