Giter VIP home page Giter VIP logo

tracerr's Introduction

Golang Errors with Stack Trace and Source Fragments

GoDoc Report Coverage Status Build Status

Tired of uninformative error output? Probably this will be more convenient:

Output

Example

package main

import (
	"io/ioutil"

	"github.com/ztrue/tracerr"
)

func main() {
	if err := read(); err != nil {
		tracerr.PrintSourceColor(err)
	}
}

func read() error {
	return readNonExistent()
}

func readNonExistent() error {
	_, err := ioutil.ReadFile("/tmp/non_existent_file")
	// Add stack trace to existing error, no matter if it's nil.
	return tracerr.Wrap(err)
}

Find more executable examples in examples dir.

How to Use

Import

import "github.com/ztrue/tracerr"

Create New Error

err := tracerr.New("some error")

Or:

err := tracerr.Errorf("some error %d", num)

Add Stack Trace to Existing Error

If err is nil then it still be nil with no stack trace added.

err = tracerr.Wrap(err)

Print Error and Stack Trace

Stack trace will be printed only if err is of type tracerr.Error, otherwise just error text will be shown.

This will print error message and stack trace if any:

tracerr.Print(err)

This will add source code:

tracerr.PrintSource(err)

It's able to set up number of lines of code to display for each frame, which is 6 by default:

tracerr.PrintSource(err, 9)

Or to set up number of lines before and after traced line:

tracerr.PrintSource(err, 5, 2)

The same, but with color, which is much more useful:

tracerr.PrintSourceColor(err)
tracerr.PrintSourceColor(err, 9)
tracerr.PrintSourceColor(err, 5, 2)

Save Output to Variable

It's also able to save output to variable instead of printing it, which works the same way:

text := tracerr.Sprint(err)
text := tracerr.SprintSource(err)
text := tracerr.SprintSource(err, 9)
text := tracerr.SprintSource(err, 5, 2)

Get Stack Trace

Stack trace will be empty if err is not an instance of tracerr.Error.

frames := tracerr.StackTrace(err)

Or if err is of type tracerr.Error:

frames := err.StackTrace()

Get Original Error

Unwrapped error will be nil if err is nil and will be the same error if err is not an instance of tracerr.Error.

err = tracerr.Unwrap(err)

Or if err is of type tracerr.Error:

err = err.Unwrap()

Performance

Stack trace causes a performance overhead, depending on a stack trace depth. This can be insignificant in a number of situations (such as HTTP request handling), however, avoid of adding a stack trace for really hot spots where a high number of errors created frequently, this can be inefficient.

Benchmarks done on a MacBook Pro 2015 with go 1.11.

Benchmarks for creating a new error with a stack trace of different depth:

BenchmarkNew/5    200000    5646 ns/op    976 B/op   4 allocs/op
BenchmarkNew/10   200000   11565 ns/op    976 B/op   4 allocs/op
BenchmarkNew/20    50000   25629 ns/op    976 B/op   4 allocs/op
BenchmarkNew/40    20000   65833 ns/op   2768 B/op   5 allocs/op

tracerr's People

Contributors

andrii-zakurenyi avatar vvakame avatar ztrue avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tracerr's Issues

Supporting Go 1.13+ wrapped errors

Go 1.13 supports wrapping errors in a standard way.

tracerr doesn't print stack traces of wrapped errors, as it doesn't know how to look inside to see the wrapped error is a tracerr.Error.

Changing the test in print.go from

        e, ok := err.(Error)
	if !ok {
		return err.Error()
	}

to

        var e Error
	if !errors.As(err, &e) {
		return err.Error()
	}

It's a fairly trivial change, but does mean that it won't compile with Go 1.12 or earlier, without some minor refactoring and build flags.

Support for obtaining a stack trace without requiring this package

I made a spiritual successor of github.com/pkg/errors some time ago and in it I want to know if an error already contains a stack trace. The goal is that if a large codebase uses different packages for errors, they should work together and not hide existing recorded information, like a stack trace.

From what I am seeing in this package is that it has the same issue as github.com/pkg/errors: the return value of StackTrace() is a custom type defined in this package. So it is not possible to detect the error having this method without importing this package.

I would suggest that instead, the following interface is implemented:

type stackTracer interface {
        StackTrace() []uintptr
}

Then, it is easy to obtain a stack trace, use it, format it, and one does not have to depend on a library which created the error.

To prevent a breaking change, I have seen also the following interface being used in this package:

type goErrorsStackTracer interface {
	Callers() []uintptr
}

BTW, you are also using runtime.FuncForPC which is deprecated. And calling it runtime.FuncForPC at the time of making a stack trace is quite a performance hit. It is much better to just record a stack trace (into []uintptr) when making an error and then resolve addresses with runtime.FuncForPC when the stack is formatted (if ever).

[Feature Request]: Print last n frames.

Incredible project! Such a beautiful night and day difference.

Currently, we can control the amount of lines before and after the trace line in methods such as:

tracerr.SprintSourceColor(beforeLines, afterLines)

Is would be incredibly helpful if we could also specify the amount of stack frames printed. For example:

tracerr.SprintSourceColor(beforeLines, afterLines, stackFrameLimit)

Or some similar signature, getting everything every trace down to the runtime assembly is rather cool but in the majority of cases you only want the last 3-4 stack frames in any given trace for debugging. This will reduce output in terminal and show only the level of granularity we need.

Another potential attack vector which would potentially help performance:

Stack trace causes a performance overhead, depending on a stack trace depth

This could potentially be mitigated if an environmental variable such as STACK_FRAME_LIMIT was added to control the max stack length big-endian style. Only the last n stack frames would be tracked, and as a frame is added, the earliest frame is popped off. This would reduce the stack trace depth and potentially decrease performance overhead on deep traces.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.