err

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2022 License: BSD-3-Clause Imports: 2 Imported by: 0

README

go-error

This package can help define custom error and handle the error gracefully.

  • Define custom error.
  • Wrap the third party error.
  • Wrap context informaton.
  • Wrap additional trace information.
  • Print statck trace message.

Install

go get github.com/qw20012/go-error

Usage

Define custom error.
func devideByZero(dividend int, divisor int) (int, error) {
	if divisor == 0 {
		return 0, err.New("Business.DevideByZero", "Given parameter divisor is zero in method devideByZero.")
	}
	return dividend / divisor, nil
}
Wrap third pary error and relative context information.
func callThirdParty(id int, value int) (int, error) {
	r, e := thirdPartyMethod(id, value)
	if e != nil {
		params := make(map[string]any)
		params["id"] = id
		params["value"] = value
		err.New("ThirdParty.BadArgument", e, params)
	}
	return r, nil
}
Wrap trace and relative context information.
func callDevideByZero(dividend int, divisor int) (int, error) {
	r, e := devideByZero(dividend, divisor)
	if e != nil {
		return 0, e.(*err.BqError).Wrap("Method callDevideByZero({dividend}, {divisor})").
		              WithParameter("dividend", dividend).WithParameter("divisor", divisor)
		 
	}
	return r, nil
}
Check error kind and handle it.
func callAndHandleError() {
	_, e := callDevideByZero(2, 0)
	if e != nil {
		bqError := e.(*err.BqError)
		if bqError.Id() == "Business.DevideByZero" {
			fmt.Println("second is,: ", bqError)
		}
	}
}

Contributing

PRs accepted.

License

BSD-style © Barret Qin

Documentation

Overview

Help error handling gracefully.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BqError

type BqError struct {
	// contains filtered or unexported fields
}

func New

func New(id string, params ...any) *BqError

New BqError pointer with given id and message. Parameter cause and parameters are optional.

func (*BqError) Cause

func (e *BqError) Cause() error

Get cause field.

func (*BqError) Error

func (e *BqError) Error() string

Stack trace error message.

func (*BqError) Id

func (e *BqError) Id() string

Get id field.

func (*BqError) Message

func (e *BqError) Message() string

Get formated message with parameters.

func (*BqError) WithParameter

func (e *BqError) WithParameter(name string, value any) *BqError

Set parameter in build pattern.

func (*BqError) Wrap

func (e *BqError) Wrap(prefix string) *BqError

Wrap message with given prefix.

Jump to

Keyboard shortcuts

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