failure is a utility package for handling application errors.
failure is a utility package for handling application errors.
Package failure is an error handling library for Go. It allows you to create, wrap, and handle errors with additional context and features.
To install failure, use the following command:
go get github.com/morikuni/failure/v2First, define your application's error codes:
type ErrorCode string
const (
ErrNotFound ErrorCode = "NotFound"
ErrInvalidArgument ErrorCode = "InvalidArgument"
)Use failure.New to create a new error with an error code:
err := failure.New(ErrNotFound, failure.Message("Resource not found"))Use failure.Wrap to wrap an existing error with additional context:
if err != nil {
return failure.Wrap(err, failure.Context{"parameter": "value"})
}Use failure.Is to check for a specific error code and handle the error:
if failure.Is(err, ErrNotFound) {
// Handle ErrNotFound error
}Use utility functions to extract metadata from the error:
code := failure.CodeOf(err)
message := failure.MessageOf(err)
callStack := failure.CallStackOf(err)Example error outputs:
err := failure.New(ErrInvalidArgument, failure.Message("Invalid argument"), failure.Context{"userId": "123"})
fmt.Println(err)
// Output: GetUser[InvalidArgument](Invalid argument, {userId=123})
fmt.Printf("%+v\n", err)
// Output:
// [main.GetUser] /path/to/file.go:123
// InvalidArgument
// Invalid argument
// {userId=123}
// [CallStack]
// [main.GetUser] /path/to/file.go:123
// [main.main] /path/to/main.go:456For more detailed usage and examples, refer to the Go Reference.
…See docs/v1-to-v2.md for migration guide.
Contributions are welcome! Feel free to send issues or pull requests.
This project is licensed under the MIT License. See the LICENSE file for details.
No open issues yet, or sync has not completed.