亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 go 中使用 pkg/errors 打印錯誤行號?

如何在 go 中使用 pkg/errors 打印錯誤行號?

Go
慕少森 2022-06-27 11:18:59
我能夠用juju/errors打印錯誤的行號,但不知道如何用pkg/errors做同樣的事情。package mainimport (    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 directorygo-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
查看完整描述

1 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

使用默認方法時,來自的錯誤pkg/errors不會打印堆棧,而是使用打印它。String()"%+v"


這在文檔的格式化打印錯誤部分中進行了解釋:


從這個包返回的所有錯誤值都實現了 fmt.Formatter 并且可以被 fmt 包格式化。支持以下動詞:


%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,則不需要使用WithStack,errors.New已經為您完成了,如本操場示例所示:


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


查看完整回答
反對 回復 2022-06-27
  • 1 回答
  • 0 關注
  • 204 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號