Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@perillo
Last active November 23, 2015 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perillo/f0eeb79a938e82c981d5 to your computer and use it in GitHub Desktop.
Save perillo/f0eeb79a938e82c981d5 to your computer and use it in GitHub Desktop.
Go errors with source file and line number
package errors
import (
"errors"
"fmt"
"runtime"
)
type errorDebug struct {
error
file string
line int
}
func New(s string) error {
err := errors.New(s)
_, file, line, _ := runtime.Caller(1)
return &errorDebug{err, file, line}
}
func Errorf(format string, a ...interface{}) error {
// We can not simply do: return New(fmt.Sprintf(format, a...))
err := fmt.Errorf(format, a...)
_, file, line, _ := runtime.Caller(1)
return &errorDebug{err, file, line}
}
func (e *errorDebug) Error() string {
return fmt.Sprintf("%s (%s:%d)", e.error, e.file, e.line)
}
func Clone(err error) error {
_, file, line, _ := runtime.Caller(1)
return &errorDebug{err, file, line}
}
func Equal(lhs, rhs error) bool {
if lhs == rhs {
return true
}
if err, ok := lhs.(*errorDebug); ok && err.error == rhs {
return true
}
if err, ok := rhs.(*errorDebug); ok && err.error == lhs {
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment