gf/g/errors/gerror/gerror.go

82 lines
1.7 KiB
Go
Raw Normal View History

// Copyright 2019 gf 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,
// You can obtain one at https://github.com/gogf/gf.
// Package errors provides simple functions to manipulate errors.
package gerror
import (
"fmt"
"github.com/gogf/gf/g/util/gconv"
)
// New returns an error that formats as the given value.
func New(value interface{}) error {
if value == nil {
return nil
}
return NewText(gconv.String(value))
}
// NewText returns an error that formats as the given text.
func NewText(text string) error {
if text == "" {
return nil
}
return &Error{
stack: callers(),
text: text,
2019-06-30 12:54:06 +08:00
}
}
// Wrap wraps error with text.
// It returns nil if given err is nil.
func Wrap(err error, text string) error {
if err == nil {
return nil
}
return &Error{
error: err,
stack: callers(),
text: text,
}
}
// Wrapf returns an error annotating err with a stack trace
// at the point Wrapf is called, and the format specifier.
// It returns nil if given err is nil.
func Wrapf(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
return &Error{
error: err,
stack: callers(),
text: fmt.Sprintf(format, args...),
2019-06-29 23:35:32 +08:00
}
}
2019-07-09 10:40:26 +08:00
// Cause returns the root cause error.
func Cause(err error) error {
if err != nil {
if e, ok := err.(*Error); ok {
return e.Cause()
}
}
return err
}
// Stack returns the stack callers as string.
// It returns an empty string id the <err> does not support stacks.
func Stack(err error) string {
if err == nil {
return ""
}
if e, ok := err.(*Error); !ok {
return e.Stack()
}
return ""
}