add error code feature for package gerror

This commit is contained in:
John Guo
2020-12-10 23:33:24 +08:00
parent a577605726
commit 84fef8dea3
11 changed files with 188 additions and 50 deletions

View File

@ -1,4 +1,4 @@
// Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
// Copyright GoFrame Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
@ -20,10 +20,11 @@ type Error struct {
error error // Wrapped error.
stack stack // Stack array, which records the stack information when this error is created or wrapped.
text string // Error text, which is created by New* functions.
code int // Error code if necessary.
}
const (
gFILTER_KEY = "/errors/gerror/gerror"
stackFilterKey = "/errors/gerror/gerror"
)
var (
@ -49,7 +50,19 @@ func (err *Error) Error() string {
}
return err.text
}
return err.error.Error()
if err.error != nil {
err.error.Error()
}
return ""
}
// Code returns the error code.
// It returns -1 if it has no error code.
func (err *Error) Code() int {
if err == nil {
return -1
}
return err.code
}
// Cause returns the root cause error.
@ -63,7 +76,7 @@ func (err *Error) Cause() error {
if e, ok := loop.error.(*Error); ok {
// Internal Error struct.
loop = e
} else if e, ok := loop.error.(ApiCause); ok {
} else if e, ok := loop.error.(apiCause); ok {
// Other Error that implements ApiCause interface.
return e.Cause()
} else {
@ -165,7 +178,7 @@ func formatSubStack(st stack, buffer *bytes.Buffer) {
for _, p := range st {
if fn := runtime.FuncForPC(p - 1); fn != nil {
file, line := fn.FileLine(p - 1)
if strings.Contains(file, gFILTER_KEY) {
if strings.Contains(file, stackFilterKey) {
continue
}
// Avoid stack string like "<autogenerated>"