Created
October 22, 2012 05:25
-
-
Save wendal/3929839 to your computer and use it in GitHub Desktop.
扩展golang默认的errors,使其包含堆栈信息
This file contains hidden or 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 ( | |
"fmt" | |
"path" | |
"runtime" | |
) | |
type Error struct { | |
msg string | |
st string | |
} | |
// Error with stace | |
func New(msg string) error { | |
return &Error{msg, stack(3)} | |
} | |
func Newf(format string, args ...interface{}) error { | |
return &Error{fmt.Sprintf(format, args), stack(3)} | |
} | |
func (e *Error) Error() string { | |
return e.msg + e.st | |
} | |
func stack(skip int) string { | |
stk := make([]uintptr, 32) | |
str := "" | |
l := runtime.Callers(skip, stk[:]) | |
for i := 0; i < l; i++ { | |
f := runtime.FuncForPC(stk[i]) | |
name := f.Name() | |
file, line := f.FileLine(stk[i]) | |
str += fmt.Sprintf("\n %-30s [%s:%d]", name, path.Base(file), line) | |
} | |
return str | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment