Structured domain errors for Go
go test -v ./...
go get -u github.com/genesor/errorz
Create an error:
package main
import "github.com/genesor/errorz"
func SomeFunc() (*interface{}, error) {
u, err := GetUser()
if err.Error() == "no row returned" {
return nil, errorz.NewNotFoundError("not_found", "something not found")
}
// Can wrap error
if err != nil {
return nil, errorz.WrapWithNotFoundError(err, "not_found", "something not found")
}
// Can format the key
errf := errorz.NewNotFoundErrorf("user_not_found", "could not find %s user", "123-user")
...
}
Check an error type:
package main
import "github.com/genesor/errorz"
func main() {
err := MyFunc()
if errorz.IsNotFoundError(err) {
// Logic handling not found
} else {
// error is not a not found
}
// An error can be cast into its actual type using the corresponding
// AsXXXError func.
if errNF, ok := errorz.AsNotFoundError(err); ok {
fmt.Println(errNF.Code, errNF.Key)
}
...
}
- NotFound
- InvalidArgument
- InvalidData
- OutdatedResource
- ForbiddenResource
- Each specific error is generated by running
go run generator/main.go
- The template file is located here:
./generator/error_template.tmpl
- To add a new error, add an
ErrorDefinition
in therun
function frommain.go