Skip to content

Latest commit

 

History

History
81 lines (58 loc) · 1.48 KB

README.md

File metadata and controls

81 lines (58 loc) · 1.48 KB

Errors

Go Reference

Golang package to create constant sentinel errors.

Install

go get github.com/nicolasparada/go-errs

Usage

You can create your own constant sentinel errors as if they were a string.

package myapp

import (
    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.

package main

import (
    "errors"
    "fmt"

    "myapp"
    errs "github.com/nicolasparada/go-errs"
)

func main() {
    ok := errors.Is(myapp.ErrInvalidEmail, errs.InvalidArgument)
    fmt.Println(ok)
    // Output: true

    var e errs.Error
    ok = errors.As(myapp.ErrInvalidEmail, &e)
    fmt.Println(ok)
    // Output: true

    ok = 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.

package main

import (
    "errors"
    "fmt"

    "myapp"
    "github.com/nicolasparada/go-errs/httperrs"
)

func main() {
    got := httperrs.Code(myapp.ErrInvalidEmail)
    fmt.Println(got)
    // Output: 422
}