Skip to content

genesor/errorz

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

errorz

Structured domain errors for Go

Run tests

go test -v ./...

Usage

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)
   }
   ...
}

Available errors

  • NotFound
  • InvalidArgument
  • InvalidData
  • OutdatedResource
  • ForbiddenResource

Internals

  • 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 the run function from main.go

About

Golang structured errors

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages