Skip to content

Instantly share code, notes, and snippets.

@aheuermann
Last active August 29, 2015 14:04
Show Gist options
  • Save aheuermann/33549b58227b49245a1b to your computer and use it in GitHub Desktop.
Save aheuermann/33549b58227b49245a1b to your computer and use it in GitHub Desktop.
Simple Go Error with Stacktrace
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