-
-
Save lucas-code42/d40813bd8d39bc66a7802aff50d8a2f2 to your computer and use it in GitHub Desktop.
Custom errors in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ./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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module myerrors | |
go 1.21.1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ./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