Last active
November 23, 2015 14:45
-
-
Save perillo/f0eeb79a938e82c981d5 to your computer and use it in GitHub Desktop.
Go errors with source file and line number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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