通过fmt/glog或者其他包打印错误对象时,默认情况下不会输出错误堆栈信息。例如:
fmt/glog
package main import ( "fmt" "github.com/gogf/gf/v2/encoding/gjson" ) func main() { _, err := gjson.Encode(func() {}) fmt.Printf("err: %v", err) }
执行后,终端输出:
err: json.Marshal failed: json: unsupported type: func()
打印错误对象中的错误堆栈信息,应当使用%+v的格式化方式。例如:
%+v
package main import ( "fmt" "github.com/gogf/gf/v2/encoding/gjson" ) func main() { _, err := gjson.Encode(func() {}) fmt.Printf("err: %+v", err) }
err: json.Marshal failed: json: unsupported type: func() 1. json.Marshal failed 1). github.com/gogf/gf/v2/internal/json.Marshal /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/internal/json/json.go:30 2). github.com/gogf/gf/v2/encoding/gjson.Encode /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/encoding/gjson/gjson_stdlib_json_util.go:41 3). main.main /Users/john/Workspace/Go/GOPATH/src/github.com/gogf/gf/.test/main.go:10 2. json: unsupported type: func()
当对错误对象进行Wrap时,不要将错误对象打印到Wrap的错误信息中,因为Wrap时本身会将目标错误对象包裹到创建的新的错误对象内部。如果将错误信息再打印包含在错误字符串中,那么在打印错误堆栈的时候会出现错误信息重复。例如(为简化示例,这里没有打印堆栈信息):
Wrap
package main import ( "fmt" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/errors/gerror" ) func main() { _, err1 := gjson.Encode(func() {}) err2 := gerror.Wrapf(err1, `error occurred: %v`, err1) fmt.Printf("err: %v", err2) }
执行后,终端输出,可以看到,打印的错误信息出现了重复:
err: error occurred: json.Marshal failed: json: unsupported type: func(): json.Marshal failed: json: unsupported type: func()
我们将上面的示例代码修复一下,如下:
package main import ( "fmt" "github.com/gogf/gf/v2/encoding/gjson" "github.com/gogf/gf/v2/errors/gerror" ) func main() { _, err1 := gjson.Encode(func() {}) err2 := gerror.Wrap(err1, `error occurred`) fmt.Printf("err: %v", err2) }
err: error occurred: json.Marshal failed: json: unsupported type: func()