1 回答

TA貢獻1831條經(jīng)驗 獲得超10個贊
你不能用這個github.com/pkg/errors函數(shù)真正做到這一點。這是因為用于包裝的錯誤類型未導出,因此您無法將其嵌入到您自己的自定義錯誤中。
但是,鑒于您不反對使用 stdliberrors包以外的錯誤庫,以下是使用juju 錯誤包的方法(因為它的 Err 類型已導出):
package main
import (
"fmt"
"github.com/juju/errors"
)
type temporary interface {
Temporary() bool
}
func IsTemporary(err error) bool {
for {
te, ok := err.(temporary)
if ok {
return te.Temporary()
}
er, ok := err.(*errors.Err)
if ok {
err = er.Underlying()
continue
}
return false
}
}
type MyError struct {
errors.Err
isTemporary bool
}
func (e MyError) Temporary() bool {
return e.isTemporary
}
func f1() error { // imitate a function from another package, that produces an error
return errors.Errorf("f1 error")
}
func f2() error {
err := f1()
wrappedErr := errors.Annotate(err, "f2 error")
return &MyError{
Err: *wrappedErr.(*errors.Err),
isTemporary: true,
}
}
func f3() error {
err := f2()
return errors.Annotate(err, "f3 error")
}
func f4() error {
err := f3()
return errors.Annotate(err, "f4 error")
}
func main() {
err := f4()
if err != nil {
if IsTemporary(err) {
fmt.Println("temporary error")
}
if e, ok := err.(*errors.Err); ok {
fmt.Printf("oops: %+v\n", e.StackTrace())
}
}
}
- 1 回答
- 0 關注
- 112 瀏覽
添加回答
舉報