gpt4 book ai didi

go - 如何处理go中的多个错误?

转载 作者:IT王子 更新时间:2023-10-29 02:00:51 26 4
gpt4 key购买 nike

在 go 中处理多个错误的最惯用的方法是什么?

我应该尝试包装错误并返回两者吗?

if err := foo(bar, obj); err != nil {
// how to do I avoid losing this error?
err := l.fixup(obj)
if err != nil {
// but this error is the not the one from foo?
}
return err
}
return l.fixup(obj)

最佳答案

您可以使用来自 Dave Cheney 的这个很棒的包中的 Wrap 函数为您的原始错误添加上下文 https://github.com/pkg/errors

errors.Wrap 函数返回一个新错误,为原始错误添加上下文。

func Wrap(cause error, message string) error

在您的情况下,这将是:

if cause := foo(bar, obj); cause != nil {
err := l.fixup(obj)
if err != nil {
return errors.Wrap(cause, err.Error())
}
return cause
}
return l.fixup(obj)

关于go - 如何处理go中的多个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55305523/

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