fail

package module
v2.0.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2018 License: MIT Imports: 6 Imported by: 37

README

fail

Build Status codecov GoDoc Go project version Go Report Card License

Better error handling solution especially for application server.

fail provides contextual metadata to errors.

  • Stack trace
  • Additional information
  • Status code (for a HTTP server)
  • Reportability (for an integration with error reporting service)

This package was forked from creasty/apperrors.

Why

Since error type in Golang is just an interface of Error() method, it doesn't have a stack trace at all. And these errors are likely passed from function to function, you cannot be sure where the error occurred in the first place.
Because of this lack of contextual metadata, debugging is a pain in the ass.

How different from pkg/errors

📝 fail supports pkg/errors. It reuses pkg/errors's stack trace data of the innermost (root) error, and converts into fail's data type.

TBA

Create an error

func New(str string) error

New returns an error that formats as the given text.
It also annotates the error with a stack trace from the point it was called

func Errorf(format string, args ...interface{}) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error.
It also annotates the error with a stack trace from the point it was called

func Wrap(err error) error

Wrap returns an error annotated with a stack trace from the point it was called.
It returns nil if err is nil

Example: Creating a new error
ok := emailRegexp.MatchString("invalid#email.addr")
if !ok {
	return fail.New("invalid email address")
}
Example: Creating from an existing error
_, err := ioutil.ReadAll(r)
if err != nil {
	return fail.Wrap(err)
}

Annotate an error

func WithMessage(msg string) Option

WithMessage annotates with the message.

func WithStatusCode(code interface{}) Option

WithStatusCode annotates with the status code.

func WithReport() Option

WithReport annotates with the reportability.

func WithTags(tags ...string) Option

WithTags annotates with tags.

func WithParam(key string, value interface{}) Option
func WithParams(h H) Option

WithParam(s) annotates with key-value pairs.

Example: Adding all contexts
_, err := ioutil.ReadAll(r)
if err != nil {
	return fail.Wrap(
		err,
		fail.WithMessage("read failed"),
		fail.WithStatusCode(http.StatusBadRequest),
		fail.WithReport(),
	)
}

Extract context from an error

func Unwrap(err error) *Error

Unwrap extracts an underlying *fail.Error from an error.
If the given error isn't eligible for retriving context from, it returns nil

type Error struct {
	// Err is the original error (you might call it the root cause)
	Err error
	// Message is an annotated description of the error
	Message string
	// StatusCode is a status code that is desired to be used for a HTTP response
	StatusCode int
	// Report represents whether the error should be reported to administrators
	Report bool
	// StackTrace is a stack trace of the original error
	// from the point where it was created
	StackTrace StackTrace
}
Example

Here's a minimum executable example describing how fail works.

package main

import (
	"errors"

	"github.com/izumin5210/fail"
	"github.com/k0kubun/pp"
)

func errFunc0() error {
	return errors.New("this is the root cause")
}
func errFunc1() error {
	return fail.Wrap(errFunc0())
}
func errFunc2() error {
	return fail.Wrap(errFunc1(), fail.WithMessage("fucked up!"))
}
func errFunc3() error {
	return fail.Wrap(errFunc2(), fail.WithStatusCode(500), fail.WithReport())
}

func main() {
	err := errFunc3()
	pp.Println(err)
}
$ go run main.go
&fail.Error{
  Err:        &errors.errorString{s: "this is the root cause"},
  Message:    "fucked up!",
  StatusCode: 500,
  Report:     true,
  StackTrace: fail.StackTrace{
    fail.Frame{Func: "errFunc1", File: "main.go", Line: 13},
    fail.Frame{Func: "errFunc2", File: "main.go", Line: 16},
    fail.Frame{Func: "errFunc3", File: "main.go", Line: 19},
    fail.Frame{Func: "main", File: "main.go", Line: 23},
    fail.Frame{Func: "main", File: "runtime/proc.go", Line: 194},
    fail.Frame{Func: "goexit", File: "runtime/asm_amd64.s", Line: 2198},
  },
}
Example: Server-side error reporting with gin-gonic/gin

Prepare a simple middleware and modify to satisfy your needs:

package middleware

import (
	"net/http"

	"github.com/izumin5210/fail"
	"github.com/izumin5210/gin-contrib/readbody"
	"github.com/gin-gonic/gin"

	// Only for example
	"github.com/jinzhu/gorm"
	"github.com/k0kubun/pp"
)

// ReportError handles an error, changes status code based on the error,
// and reports to an external service if necessary
func ReportError(c *gin.Context, err error) {
	appErr := fail.Unwrap(err)
	if appErr == nil {
		// As it's a "raw" error, `StackTrace` field left unset.
		// And it should be always reported
		appErr = &fail.Error{
			Err:    err,
			Report: true,
		}
	}

	convertAppError(appErr)

	// Send the error to an external service
	if appErr.Report {
		go uploadAppError(c.Copy(), appErr)
	}

	// Expose an error message in the header
	if appErr.Message != "" {
		c.Header("X-App-Error", appErr.Message)
	}

	// Set status code accordingly
	if appErr.StatusCode > 0 {
		c.Status(appErr.StatusCode)
	} else {
		c.Status(http.StatusInternalServerError)
	}
}

func convertAppError(err *fail.Error) {
	// If the error is from ORM and it says "no record found,"
	// override status code to 404
	if err.Err == gorm.ErrRecordNotFound {
		err.StatusCode = http.StatusNotFound
		return
	}
}

func uploadAppError(c *gin.Context, err *fail.Error) {
	// By using readbody, you can retrive an original request body
	// even when c.Request.Body had been read
	body := readbody.Get(c)

	// Just debug
	pp.Println(string(body[:]))
	pp.Println(err)
}

And then you can use like as follows.

r := gin.Default()
r.Use(readbody.Recorder()) // Use github.com/izumin5210/gin-contrib/readbody

r.GET("/test", func(c *gin.Context) {
	err := doSomethingReallyComplex()
	if err != nil {
		middleware.ReportError(c, err) // Neither `c.AbortWithError` nor `c.Error`
		return
	}

	c.Status(200)
})

r.Run()

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Errorf

func Errorf(format string, args ...interface{}) error

Errorf formats according to a format specifier and returns the string as a value that satisfies error. It also annotates the error with a stack trace from the point it was called

func New

func New(text string) error

New returns an error that formats as the given text. It also annotates the error with a stack trace from the point it was called

func Wrap

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

Wrap returns an error annotated with a stack trace from the point it was called. It returns nil if err is nil

Types

type Error

type Error struct {
	// Err is the original error (you might call it the root cause)
	Err error
	// Message is an annotated description of the error
	Message string
	// StatusCode is a status code that is desired to be contained in responses, such as HTTP Status code.
	StatusCode interface{}
	// Report represents whether the error should be reported to administrators
	Report bool
	// Tags represents tags of the error which is classified errors.
	Tags []string
	// Params is an annotated parameters of the error.
	Params H
	// StackTrace is a stack trace of the original error
	// from the point where it was created
	StackTrace StackTrace
}

Error is an error that has contextual metadata

func Unwrap

func Unwrap(err error) *Error

Unwrap extracts an underlying *fail.Error from an error. If the given error isn't eligible for retriving context from, it returns nil

func (*Error) Copy

func (e *Error) Copy() *Error

Copy creates a copy of the current object

func (*Error) Error

func (e *Error) Error() string

Error implements error interface

type Frame

type Frame struct {
	Func string
	File string
	Line int64
}

Frame represents a single frame of stack trace

type H

type H map[string]interface{}

H represents a JSON-like key-value object.

func (H) Merge

func (h H) Merge(other map[string]interface{}) H

Merge returns a new H object contains self and other H contents.

type Option

type Option func(*Error)

Option annotates an errors.

func WithMessage

func WithMessage(msg string) Option

WithMessage annotates with the message.

func WithParam

func WithParam(key string, value interface{}) Option

WithParam annotates with a key-value pair.

func WithParams

func WithParams(h H) Option

WithParams annotates with key-value pairs.

func WithReport

func WithReport() Option

WithReport annotates with the reportability.

func WithStatusCode

func WithStatusCode(code interface{}) Option

WithStatusCode annotates with the status code.

func WithTags

func WithTags(tags ...string) Option

WithTags annotates with tags.

type StackTrace

type StackTrace []Frame

StackTrace is a stack of Frame from innermost to outermost

Jump to

Keyboard shortcuts

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