Skip to content

Instantly share code, notes, and snippets.

@lucas-code42
Forked from renanbastos93/error.go
Created January 15, 2024 01:40
Show Gist options
  • Save lucas-code42/d40813bd8d39bc66a7802aff50d8a2f2 to your computer and use it in GitHub Desktop.
Save lucas-code42/d40813bd8d39bc66a7802aff50d8a2f2 to your computer and use it in GitHub Desktop.
Custom errors in Golang
// ./custom/error.go
package myerrors
import (
"fmt"
)
type myError struct {
code int
msg string
}
func NewError(code int, msg string) error {
return &myError{
code: code,
msg: msg,
}
}
func (e myError) Error() string {
return fmt.Sprintf("%d: %s", e.code, e.msg)
}
module myerrors
go 1.21.1
// ./cmd/main.go
package main
import (
"errors"
"fmt"
myerrors "myerrors/custom"
)
func main() {
// Here, a custom error is created using the NewError function from the myerrors package.
// The error has a status code of 400 and a message of "bad request."
err := myerrors.NewError(400, "bad request")
// This line uses fmt.Errorf to create a new error (errAgain) by formatting a string.
// The %w verb is used to wrap the original error (err) within the new error.
// The message includes both the original error's message and a new custom error
// with a status code of 404 and a message of "not found."
errAgain := fmt.Errorf("%w: %v", err, myerrors.NewError(404, "not found"))
// output: 400: bad request: 404: not found
fmt.Println(errAgain)
// The errors.Is function is used to check if the error (errAgain) contains the wrapped error (err).
// It returns true if errAgain is an instance of err or if err is one of the wrapped errors within errAgain.
fmt.Println(errors.Is(errAgain, err))
// The errors.Unwrap function is used to retrieve the original error that was wrapped.
// In this case, it returns the original error (err), removing the additional wrapping
fmt.Println(errors.Unwrap(errAgain))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment