improve error handling for gconv.Struct/ghttp.Server; add NewSkip/NewfSkip function for package gerror

This commit is contained in:
John
2020-04-28 15:04:07 +08:00
parent 9e064e2651
commit 6e7224e306
10 changed files with 180 additions and 59 deletions

View File

@ -5,6 +5,9 @@
// You can obtain one at https://github.com/gogf/gf.
// Package errors provides simple functions to manipulate errors.
//
// Very note that, this package is quite a base package, which should not import extra
// packages except standard packages, to avoid cycle imports.
package gerror
import (
@ -13,11 +16,13 @@ import (
// ApiStack is the interface for Stack feature.
type ApiStack interface {
Error() string // It should be en error.
Stack() string
}
// ApiCause is the interface for Cause feature.
type ApiCause interface {
Error() string // It should be en error.
Cause() error
}
@ -32,6 +37,18 @@ func New(text string) error {
}
}
// NewSkip creates and returns an error which is formatted from given text.
// The parameter <skip> specifies the stack callers skipped amount.
func NewSkip(skip int, text string) error {
if text == "" {
return nil
}
return &Error{
stack: callers(skip),
text: text,
}
}
// Newf returns an error that formats as the given format and args.
func Newf(format string, args ...interface{}) error {
if format == "" {
@ -43,6 +60,18 @@ func Newf(format string, args ...interface{}) error {
}
}
// NewfSkip returns an error that formats as the given format and args.
// The parameter <skip> specifies the stack callers skipped amount.
func NewfSkip(skip int, format string, args ...interface{}) error {
if format == "" {
return nil
}
return &Error{
stack: callers(skip),
text: fmt.Sprintf(format, args...),
}
}
// Wrap wraps error with text.
// It returns nil if given err is nil.
func Wrap(err error, text string) error {

View File

@ -9,7 +9,6 @@ package gerror
import (
"bytes"
"fmt"
"github.com/gogf/gf/internal/intlog"
"io"
"runtime"
"strings"
@ -131,15 +130,6 @@ func formatSubStack(st stack, buffer *bytes.Buffer) {
if strings.Contains(file, gFILTER_KEY) {
continue
}
// Avoid GF stacks if not in GF development.
if !intlog.IsEnabled() {
if strings.Contains(file, "github.com/gogf/gf/") {
continue
}
if strings.Contains(file, "github.com/gogf/gf@") {
continue
}
}
// Avoid stack string like "<autogenerated>"
if strings.Contains(file, "<") {
continue

View File

@ -15,8 +15,14 @@ const (
gMAX_STACK_DEPTH = 32
)
func callers() stack {
var pcs [gMAX_STACK_DEPTH]uintptr
n := runtime.Callers(3, pcs[:])
return pcs[0:n]
// callers returns the stack callers.
func callers(skip ...int) stack {
var (
pcs [gMAX_STACK_DEPTH]uintptr
n = 3
)
if len(skip) > 0 {
n += skip[0]
}
return pcs[:runtime.Callers(n, pcs[:])]
}