Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nicolasparada/go-errs
Golang constant error sentinels
https://github.com/nicolasparada/go-errs
error errors go-module go-package
Last synced: 6 days ago
JSON representation
Golang constant error sentinels
- Host: GitHub
- URL: https://github.com/nicolasparada/go-errs
- Owner: nicolasparada
- License: isc
- Created: 2022-06-26T19:02:19.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-08-05T03:03:24.000Z (over 1 year ago)
- Last Synced: 2024-04-14T07:10:36.087Z (7 months ago)
- Topics: error, errors, go-module, go-package
- Language: Go
- Homepage:
- Size: 12.7 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Errors
[![Go Reference](https://pkg.go.dev/badge/github.com/nicolasparada/go-errs.svg)](https://pkg.go.dev/github.com/nicolasparada/go-errs)
Golang package to create constant sentinel errors.
## Install
```bash
go get github.com/nicolasparada/go-errs
```## Usage
You can create your own constant sentinel errors as if they were a string.
```go
package myappimport (
errs "github.com/nicolasparada/go-errs"
)const (
ErrInvalidEmail = errs.InvalidArgumentError("myapp: invalid email")
)
```You can use `errors.Is` to check for the error group, which are exposed in the package.
Or you can use `errors.As` to check if your error is of type `errs.Error` so you can extract the error kind as well.
```go
package mainimport (
"errors"
"fmt""myapp"
errs "github.com/nicolasparada/go-errs"
)func main() {
ok := errors.Is(myapp.ErrInvalidEmail, errs.InvalidArgument)
fmt.Println(ok)
// Output: truevar e errs.Error
ok = errors.As(myapp.ErrInvalidEmail, &e)
fmt.Println(ok)
// Output: trueok = e.Kind() == errs.KindInvalidArgument
fmt.Println(ok)
// Output: true
}
```## HTTP Errors
You can use the `httperrs` subpackage to quickly convert an error
defined using this package into an HTTP status code.```go
package mainimport (
"errors"
"fmt""myapp"
"github.com/nicolasparada/go-errs/httperrs"
)func main() {
got := httperrs.Code(myapp.ErrInvalidEmail)
fmt.Println(got)
// Output: 422
}
```