gpt4 book ai didi

go - 如何在go中显示带有pkg/errors的错误行号?

转载 作者:行者123 更新时间:2023-12-01 22:02:42 26 4
gpt4 key购买 nike

我可以使用juju/errors打印错误的行号,但不确定如何使用pkg/errors进行操作。

package main

import (
jerrors "github.com/juju/errors"
perrors "github.com/pkg/errors"

"io/ioutil"
"log"
)

func jerror() error {
//throw an error....
_, err := ioutil.ReadDir("r")
if err != nil {
return jerrors.Trace(err)
}
return nil
}

func perror() error {
//throw an error....
_, err := ioutil.ReadDir("r")
if err != nil {
return perrors.Cause(err)
}
return nil
}

func main() {
jerr := jerror()
if jerr != nil {
log.Println(jerrors.ErrorStack(jerr))
}

log.Println("-------------------------")

perr := perror()
if perr != nil {
log.Println(perrors.WithStack(perr))
}
}
打印输出:
2020/08/26 00:19:48 open r: no such file or directory
go-mock-json-api/main.go:15:
2020/08/26 00:19:48 -------------------------
2020/08/26 00:19:48 open r: no such file or directory

最佳答案

使用默认的pkg/errors方法时,String()的错误将不会打印堆栈,使用"%+v"而不是来打印堆栈。
在文档的formatted printing of errors部分中对此进行了解释:

All error values returned from this package implement fmt.Formatter and can be formatted by the fmt package. The following verbs are supported:

%s    print the error. If the error has a Cause it will be
printed recursively.
%v see %s
%+v extended format. Each Frame of the error's StackTrace will
be printed in detail.

WithStack的文档提供了显示不同行为的示例:
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Println(err)

// Output:
// whoops

fmt.Printf("%+v", err)

// Output:
// whoops
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
// testing.runExample
// ...
请注意,如果您直接使用 errors.New,则不需要使用 WithStackerrors.New已经为您做到了,如下面的 playground example所示:
package main

import (
"fmt"

"github.com/pkg/errors"
)

func main() {
err := errors.New("whoops")
fmt.Printf("String: %s\n", err)
fmt.Printf("Verbose: %+v\n", err)

}
输出:
String: whoops
Verbose: whoops
main.main
/tmp/sandbox878560423/prog.go:10
runtime.main
/usr/local/go-faketime/src/runtime/proc.go:204
runtime.goexit
/usr/local/go-faketime/src/runtime/asm_amd64.s:1374

关于go - 如何在go中显示带有pkg/errors的错误行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63592514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com