Skip to content

Latest commit

 

History

History
109 lines (74 loc) · 2.18 KB

README.md

File metadata and controls

109 lines (74 loc) · 2.18 KB

Go Error

The Go Error library implements runtime error with message string formatted using replacement fields surrounded by curly braces {} format strings from the Go Formatter library.

[[TOC]]

Features

  • Format string by providing arguments without using placeholders or format verbs %
  • Format string using automatic placeholder {p}
  • Format string using positional placeholders {pN}
  • Format string using named placeholders {name}
  • Format string using object placeholders {.Field}, {p.Field} and {pN.Field} where Field is an exported struct field or method
  • Set custom format error message string. Default is {.Package}:{.FileBase}:{.Line}:{.FunctionBase}(): {.String}
  • Error message contains file path, line number, function name from where was called
  • Compatible with the standard errors package with As, Is and Unwrap functions
  • It uses the Go Formatter library

Usage

Import rterror package:

import "gitlab.com/tymonx/go-error/rterror"

Without arguments

err := rterror.New("Error message")

fmt.Println(err)

Output:

<file>:<line>:<function>(): Error message

With arguments

err := rterror.New("Error message {p1} -", 3, "bar")

fmt.Println(err)

Output:

<file>:<line>:<function>(): Error message bar - 3

Wrapped

wrapped := rterror.New("Wrapped error")

err := rterror.New("Error message {p1} -", 3, "bar").Wrap(wrapped)

fmt.Println(errors.Is(err, wrapped))

Output:

true

Custom format

err := rterror.New("Error message {p1} -", 3, "bar").SetFormat("#{.Function} := '{.String}' <-")

fmt.Println(err)

Output:

#<function> := 'Error message bar - 3' <-

Custom error type

type MyError struct {
    rterror.RuntimeError
}

func New(message string, arguments ...interface{}) *MyError {
    return &MyError{
        RuntimeError: *rterror.NewSkipCaller(rterror.SkipCall, message, arguments...),
    }
}

err := New("My custom error")

fmt.Println(err)

Output:

<file>:<line>:<function>(): My custom error