Last active
August 29, 2015 14:04
-
-
Save aheuermann/33549b58227b49245a1b to your computer and use it in GitHub Desktop.
Simple Go Error with Stacktrace
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 err | |
import ( | |
"fmt" | |
"runtime/debug" | |
) | |
type Err struct { | |
errorWithStack string | |
} | |
func (err Err) Error() string { | |
return err.errorWithStack | |
} | |
func createError(msg string, stack []byte) error { | |
return &Err{fmt.Sprintf("%s\n%s", msg, string(stack))} | |
} | |
func NewError(err interface{}) error { | |
if err == nil { | |
return nil | |
} | |
stack := debug.Stack() | |
switch v := err.(type) { | |
case string: | |
return createError(v, stack) | |
case *Err: | |
return v | |
case Err: | |
return v | |
case error: | |
return createError(v.Error(), stack) | |
} | |
return NewError("Unrecognized error type....") | |
} | |
func NewErrorf(format string, a ...interface{}) error { | |
stack := debug.Stack() | |
return createError(fmt.Sprintf(format, a), stack) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment