Package errors provides simple error handling primitives. Migrated from golib.
Based on github.com/pkg/errors, and fully compatible with github.com/pkg/errors
.
package main
import (
"fmt"
"net/http"
"github.com/shipengqi/errors"
)
type fakeCoder struct {
code int
status int
msg string
ref string
}
func (d fakeCoder) Code() int { return d.code }
func (d fakeCoder) String() string { return d.msg }
func (d fakeCoder) Reference() string { return d.ref }
func (d fakeCoder) HTTPStatus() int {
if d.status == 0 {
return http.StatusInternalServerError
}
return d.status
}
type parseCoder struct {
code int
}
func (d parseCoder) Code() int { return d.code }
func main() {
// annotates err with a code.
codeErr := errors.WithCode(fmt.Errorf("demo error"), 20010)
// reports whether any error in err's contains the given code.
fmt.Println(errors.IsCode(codeErr, 20010)) // true
// returns an error annotating err with a code and a stack trace at the point WrapCodef is called.
_ = errors.WrapCode(fmt.Errorf("demo error"), 20011)
// returns an error annotating err with a code and a stack trace at the point WrapCodef is called, and the format specifier.
_ = errors.WrapCodef(fmt.Errorf("wrap error"), 20012, "wrap %s", "demo")
demoCoder := fakeCoder{
code: 20013,
status: http.StatusBadRequest,
msg: "bad request",
ref: "https://docs.example.com/codes",
}
// registers a Coder to the global cache.
errors.Register(demoCoder)
// parse any error into icoder interface, find the corresponding Coder from global cache.
errors.ParseCoder(parseCoder{code: 20013})
}
package main
import (
"fmt"
"github.com/shipengqi/errors"
)
func main() {
// Aggregate represents an object that contains multiple errors, but does not
// necessarily have singular semantic meaning
var errs []error
errs = append(errs,
errors.New("error 1"),
errors.New("error 2"),
errors.New("error 3"),
)
agge := errors.NewAggregate(errs)
fmt.Println(agge.Error()) // [error 1, error 2, error 3]
}
You can find the docs at go docs.
errors
had been being developed with GoLand under the free JetBrains Open Source license(s) granted by JetBrains s.r.o., hence I would like to express my thanks here.