errs

package module
v1.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 22, 2021 License: Apache-2.0 Imports: 7 Imported by: 0

README

errs -- Error handling for Golang

check vulns lint status GitHub license GitHub release

Package errs implements functions to manipulate error instances. This package is required Go 1.13 or later.

Usage

Create new error instance with cause
package main

import (
    "fmt"
    "os"

    "github.com/spiegel-im-spiegel/errs"
)

func checkFileOpen(path string) error {
    file, err := os.Open(path)
    if err != nil {
        return errs.New(
            "file open error",
            errs.WithCause(err),
            errs.WithContext("path", path),
        )
    }
    defer file.Close()

    return nil
}

func main() {
    if err := checkFileOpen("not-exist.txt"); err != nil {
        fmt.Printf("%v\n", err)             // file open error: open not-exist.txt: no such file or directory
        fmt.Printf("%#v\n", err)            // *errs.Error{Err:&errors.errorString{s:"file open error"}, Cause:&fs.PathError{Op:"open", Path:"not-exist.txt", Err:0x2}, Context:map[string]interface {}{"function":"main.checkFileOpen", "path":"not-exist.txt"}}
        fmt.Printf("%+v\n", err)            // {"Type":"*errs.Error","Err":{"Type":"*errors.errorString","Msg":"file open error"},"Context":{"function":"main.checkFileOpen","path":"not-exist.txt"},"Cause":{"Type":"*fs.PathError","Msg":"open not-exist.txt: no such file or directory","Cause":{"Type":"syscall.Errno","Msg":"no such file or directory"}}}
        fmt.Printf("%v\n", errs.Cause(err)) // no such file or directory
    }
}
Wrapping error instance
package main

import (
    "fmt"
    "os"

    "github.com/spiegel-im-spiegel/errs"
)

func checkFileOpen(path string) error {
    file, err := os.Open(path)
    if err != nil {
        return errs.Wrap(
            err,
            errs.WithContext("path", path),
        )
    }
    defer file.Close()

    return nil
}

func main() {
    if err := checkFileOpen("not-exist.txt"); err != nil {
        fmt.Printf("%v\n", err)             // open not-exist.txt: no such file or directory
        fmt.Printf("%#v\n", err)            // *errs.Error{Err:&fs.PathError{Op:"open", Path:"not-exist.txt", Err:0x2}, Cause:<nil>, Context:map[string]interface {}{"function":"main.checkFileOpen", "path":"not-exist.txt"}}
        fmt.Printf("%+v\n", err)            // {"Type":"*errs.Error","Err":{"Type":"*fs.PathError","Msg":"open not-exist.txt: no such file or directory","Cause":{"Type":"syscall.Errno","Msg":"no such file or directory"}},"Context":{"function":"main.checkFileOpen","path":"not-exist.txt"}}
        fmt.Printf("%v\n", errs.Cause(err)) // no such file or directory
    }
}
Wrapping error instance with cause
package main

import (
    "errors"
    "fmt"
    "os"

    "github.com/spiegel-im-spiegel/errs"
)

func checkFileOpen(path string) error {
    file, err := os.Open(path)
    if err != nil {
        return errs.Wrap(
            errors.New("file open error"),
            errs.WithCause(err),
            errs.WithContext("path", path),
        )
    }
    defer file.Close()

    return nil
}

func main() {
    if err := checkFileOpen("not-exist.txt"); err != nil {
        fmt.Printf("%v\n", err)             // file open error: open not-exist.txt: no such file or directory
        fmt.Printf("%#v\n", err)            // *errs.Error{Err:&errors.errorString{s:"file open error"}, Cause:&fs.PathError{Op:"open", Path:"not-exist.txt", Err:0x2}, Context:map[string]interface {}{"function":"main.checkFileOpen", "path":"not-exist.txt"}}
        fmt.Printf("%+v\n", err)            // {"Type":"*errs.Error","Err":{"Type":"*errors.errorString","Msg":"file open error"},"Context":{"function":"main.checkFileOpen","path":"not-exist.txt"},"Cause":{"Type":"*fs.PathError","Msg":"open not-exist.txt: no such file or directory","Cause":{"Type":"syscall.Errno","Msg":"no such file or directory"}}}
        fmt.Printf("%v\n", errs.Cause(err)) // no such file or directory
    }
}

Documentation

Overview

Package errs implements functions to manipulate error instances.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func As

func As(err error, target interface{}) bool

As is conpatible with errors.As.

func Cause

func Cause(err error) error

Cause function finds cause error in target error instance.

Example
package main

import (
	"fmt"
	"os"

	"github.com/spiegel-im-spiegel/errs"
)

func main() {
	_, err := os.Open("not-exist.txt")
	fmt.Printf("%v", errs.Cause(err))
}
Output:

no such file or directory

func EncodeJSON added in v0.2.0

func EncodeJSON(err error) string

EncodeJSON function dumps out error instance with JSON format.

Example
package main

import (
	"fmt"
	"os"

	"github.com/spiegel-im-spiegel/errs"
)

func main() {
	_, err := os.Open("not-exist.txt")
	fmt.Printf("%v", errs.EncodeJSON(err))
}
Output:

{"Type":"*fs.PathError","Msg":"open not-exist.txt: no such file or directory","Cause":{"Type":"syscall.Errno","Msg":"no such file or directory"}}

func Is

func Is(err, target error) bool

Is is conpatible with errors.Is.

func New added in v0.2.0

func New(msg string, opts ...ErrorContextFunc) error

New function returns an error instance with message and context informations.

Example
package main

import (
	"fmt"
	"os"

	"github.com/spiegel-im-spiegel/errs"
)

func main() {
	err := errs.New(
		"wrapper error",
		errs.WithCause(os.ErrInvalid),
		errs.WithContext("foo", "bar"),
	)
	fmt.Printf("%+v", err)
}
Output:

{"Type":"*errs.Error","Err":{"Type":"*errors.errorString","Msg":"wrapper error"},"Context":{"foo":"bar","function":"github.com/spiegel-im-spiegel/errs_test.ExampleNew"},"Cause":{"Type":"*errors.errorString","Msg":"invalid argument"}}

func Unwrap added in v0.4.0

func Unwrap(err error) error

Unwrap is conpatible with errors.Unwrap.

func Wrap

func Wrap(err error, opts ...ErrorContextFunc) error

Wrap function returns a wrapping error instance with context informations.

Types

type Error added in v0.2.0

type Error struct {
	Err     error
	Cause   error
	Context map[string]interface{}
	// contains filtered or unexported fields
}

Error type is a implementation of error interface. This type is for wrapping cause error instance.

Example
package main

import (
	"fmt"
	"os"

	"github.com/spiegel-im-spiegel/errs"
)

func main() {
	err := errs.Wrap(
		os.ErrInvalid,
		errs.WithContext("foo1", "bar1"),
	)
	_ = err.(*errs.Error).SetContext("foo2", "bar2")
	fmt.Printf("%+v", err)
}
Output:

{"Type":"*errs.Error","Err":{"Type":"*errors.errorString","Msg":"invalid argument"},"Context":{"foo1":"bar1","foo2":"bar2","function":"github.com/spiegel-im-spiegel/errs_test.ExampleError"}}

func (*Error) EncodeJSON added in v0.4.0

func (e *Error) EncodeJSON() string

EncodeJSON method returns serialize string of Error with JSON format.

func (*Error) Error added in v0.2.0

func (e *Error) Error() string

Error method returns error message. This method is a implementation of error interface.

func (*Error) Format added in v0.2.0

func (e *Error) Format(s fmt.State, verb rune)

Format method returns formatted string of Error instance. This method is a implementation of fmt.Formatter interface.

func (*Error) GoString added in v0.2.0

func (e *Error) GoString() string

GoString method returns serialize string of Error. This method is a implementation of fmt.GoStringer interface.

func (*Error) Is added in v0.2.0

func (e *Error) Is(target error) bool

Is method reports whether any error in error's chain matches cause of target error. This method is used in errors.Is function.

func (*Error) MarshalJSON added in v0.3.0

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON method returns serialize string of Error with JSON format. This method is implementation of json.Marshaler interface.

func (*Error) SetCause added in v0.7.0

func (e *Error) SetCause(err error) *Error

SetCause method sets cause error instance

func (*Error) SetContext added in v0.3.0

func (e *Error) SetContext(name string, value interface{}) *Error

SetContext method sets context information

func (*Error) String added in v0.2.0

func (e *Error) String() string

String method returns error message. This method is a implementation of fmt.Stringer interface.

func (*Error) Unwrap added in v0.2.0

func (e *Error) Unwrap() error

Unwrap method returns cause error in Error instance. This method is used in errors.Unwrap function.

type ErrorContextFunc added in v0.3.0

type ErrorContextFunc func(*Error)

ErrorContextFunc type is self-referential function type for New and Wrap functions. (functional options pattern)

func WithCause added in v0.7.0

func WithCause(err error) ErrorContextFunc

WithCause function returns ErrorContextFunc function value. This function is used in New and Wrap functions that represents context (key/value) data.

func WithContext added in v0.3.0

func WithContext(name string, value interface{}) ErrorContextFunc

WithContext function returns ErrorContextFunc function value. This function is used in New and Wrap functions that represents context (key/value) data.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL