Just another error handling primitives for golang

errors

Just another error handling primitives for golang

Install

go install github.com/WAY29/errors@latest

Usage

New error and print error context

The errors.New()/errors.Newf() function returns a new error that has a context, and you can use "%+v" as format descriptor to print error context. For example

err := errors.New("an_error")
fmt.Printf("%+v", err) // will print error message and context information

Print error message

err := errors.New("an_error")
fmt.Printf("%+v", err) // will print error message and context information
fmt.Printf("%#v", err) // will only print error context information
fmt.Printf("%v", err) // will only print error message
fmt.Printf("%s", err) // will only print error message

Adding context to an error

The errors.Wrap()/errors.Wrapf() function returns a new error that adds context to the original error. For example

_, err := ioutil.ReadAll(r)
if err != nil {
        return errors.Wrap(err, "read failed")
}

Adding error type to an error

The errors.SetType() function returns a new error that adds error type to wrapped error. For example

type ErrorType uint16

const (
	RequestError ErrorType = iota
	ResponseError
)


func test() {
	err := errors.New("new error")
	err, _ = errors.SetType(err, RequestError)
	// or errors.SetTypeWithoutBool
	// err = errors.SetTypeWithoutBool(err, RequestError)

	switch errType := errors.GetType(err); errType {
	case RequestError:
		fmt.Printf("Request error: %+v\n", err)
	case ResponseError:
		fmt.Printf("Response error: %+v\n", err)
	default:
		fmt.Printf("Unknown error: %#v\n", err)
	}
}

Adding more information to an error

The errors.Wrap()/errors.Wrapf() function can also be used to add additional information to wrapped errors. For example

err := errors.New("an_error")
err = errors.Wrap(err, "more information")
fmt.Printf("%+v", err) // will print error message and context information

Retrieving the cause of an error

Using errors.Wrap() constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by errors.Cause.

type causer interface {
        Cause() error
}

errors.Cause will recursively retrieve the topmost error which does not implement causer, which is assumed to be the original cause. For example:

switch err := errors.Cause(err).(type) {
case *MyError:
        // handle specifically
default:
        // unknown error
}

How I use this library

For example

package errors

import (
	"fmt"
	"github.com/WAY29/errors"
)

type ErrorType uint16

const (
	RequestError ErrorType = iota
	ResponseError
)

func main() {
	// errors.SetCurrentAbsPath()

	err := errors.New("new error")
	err, _ = errors.SetType(err, RequestError)
	err = errors.Wrapf(err, "wrapped")

	switch errType := errors.GetType(err); errType {
	case RequestError:
		fmt.Printf("Request error: %+v\n", err)
	case ResponseError:
		fmt.Printf("Response error: %+v\n", err)
	default:
		fmt.Printf("Unknown error: %#v\n", err)
	}
}

Benchmark

BenchmarkError1000
BenchmarkError1000-16
 2483836	       461.6 ns/op	      48 B/op	       2 allocs/op
BenchmarkError10000
BenchmarkError10000-16
 2560116	       459.6 ns/op	      48 B/op	       2 allocs/op
BenchmarkWrappedError1000
BenchmarkWrappedError1000-16
  933684	      1283 ns/op	     360 B/op	      11 allocs/op
BenchmarkWrappedError10000
BenchmarkWrappedError10000-16
  958335	      1263 ns/op	     360 B/op	      11 allocs/op

Notice

  • If you run golang files by go run, please run errors.SetCurrentAbsPath() first, or stack message about path will be absolute path.
  • If you want to skip some frame about stack, please run errors.SetSkipFrameNum(skipNum), this is usually used for your secondary encapsulation of the library.

Reference

Similar Resources

Wraps the normal error and provides an error that is easy to use with net/http.

Go HTTP Error Wraps the normal error and provides an error that is easy to use with net/http. Install go get -u github.com/cateiru/go-http-error Usage

Dec 20, 2021

Wrap contains a method for wrapping one Go error with another.

Note: this code is still in alpha stage. It works but it may change subtly in the near future, depending on what comes out of golang/go#52607. Wrap.Wi

Jun 27, 2022

A Go (golang) package for representing a list of errors as a single error.

go-multierror go-multierror is a package for Go that provides a mechanism for representing a list of error values as a single error. This allows a fun

Jan 1, 2023

Golang advanced error usage with stack tracing

UhOh Golang advanced error usage with stack tracing uhoh consists of 3 parts: Original error Description of error Stack trace File Function Line Usage

Mar 30, 2022

Reduce debugging time while programming Go. Use static and stack-trace analysis to determine which func call causes the error.

Reduce debugging time while programming Go. Use static and stack-trace analysis to determine which func call causes the error.

Errlog: reduce debugging time while programming Introduction Use errlog to improve error logging and speed up debugging while you create amazing code

Nov 18, 2022

A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Dec 6, 2022

Error tracing and annotation.

errors -- import "github.com/juju/errgo" The errors package provides a way to create and diagnose errors. It is compatible with the usual Go error idi

Nov 3, 2022

A flexible error support library for Go

errors Please see http://godoc.org/github.com/spacemonkeygo/errors for info License Copyright (C) 2014 Space Monkey, Inc. Licensed under the Apache Li

Nov 3, 2022

A powerful, custom error package for Go

custom-error-go A powerful, custom error package for Go Detailed explanation: https://medium.com/codealchemist/error-handling-in-go-made-more-powerful

Apr 19, 2022
A comprehensive error handling library for Go

Highlights The errorx library provides error implementation and error-related utilities. Library features include (but are not limited to): Stack trac

Jan 6, 2023
Declarative error handling for Go.

ErrorFlow Declarative error handling for Go. Motivation Reading list: Don't defer Close() on writable files Error Handling — Problem Overview Proposal

Mar 3, 2022
Generic error handling with panic, recover, and defer.

Generic error handling with panic, recover, and defer.

Aug 25, 2022
brief: a piece of error handling codelet

brief a piece of error handling codelet. this code only demonstrates how to hide sql.ErrNoRows to the caller. the Get() method defined in the pkg/proj

Oct 30, 2021
🥷 CError (Custom Error Handling)

?? CError (Custom Error Handling) Installation Via go packages: go get github.com/rozturac/cerror Usage Here is a sample CError uses: import ( "gi

Sep 21, 2022
Errors - A lib for handling error gracefully in Go

?? Errors Errors 是一个用于优雅地处理 Go 中错误的库。 Read me in English ??‍ 功能特性 优雅地处理 error,嗯,

Jan 17, 2022
Simple, intuitive and effective error handling for Go

Error Handling with eluv-io/errors-go The package eluv-io/errors-go makes Go error handling simple, intuitive and effective. err := someFunctionThatCa

Jan 19, 2022
Error handling hook & helper function to simplify writing API handler methods in Go.

Error handling hook & helper function to simplify writing API handler methods in Go.

Jan 19, 2022
Try - Idiomatic monadic-ish error handling for go

Try Idiomatic monadic-ish error handling for go. Examples import

Jan 24, 2022
Go error library with error portability over the network

cockroachdb/errors: Go errors with network portability This library aims to be used as a drop-in replacement to github.com/pkg/errors and Go's standar

Dec 29, 2022