英文:
Golang use of Zerolog and raising errors
问题
我正在使用zerolog在我的Go应用程序中进行日志记录,并且我正在尝试遵循只在堆栈顶部出错的最佳实践。然而,我不确定如何同时写入错误日志并将错误传递给上层链:
func VeryDeepFunction() (int, error) {
err := doSomethingThatCouldCauseError()
if err != nil {
errMsg := fmt.Sprintf("something bad happened: %+v", err)
log.Error().Msgf(errMsg)
return 0, fmt.Errorf(errMsg)
}
return 1, nil
}
对我来说,这种方式感觉有些冗余 - 格式化字符串,使用zerolog记录,然后再次包装错误。有没有更正确的方法来做这个?
英文:
I'm using zerolog to do logging in my Go app, and I'm trying to follow best practices for only erroring out at the top of the stack. However, I'm not sure exactly how to write both to my error log and pass the error up the chain:
func VeryDeepFunction() (int, error) {
err := doSomethingThatCouldCauseError()
if err != nil {
errMsg := fmt.Sprintf("something bad happened: %+v", err)
log.Error().Msgf(errMsg)
return 0, fmt.Errorf(errMsg)
}
return 1, nil
}
This feels redundant to me - formatting the string, filing with zerolog, and then wrapping the error again. Is there a more correct way to do this?
答案1
得分: 1
可以将错误链接在一起。
package main
import (
"log"
"github.com/pkg/errors"
)
var someError = errors.New("something is wrong")
func main() {
// 在顶层处理错误
if err := someFunc(); errors.Is(err, someError) {
log.Println(err)
}
}
func someFunc() error {
if err := alwaysError(); err != nil {
return errors.Wrap(err, "someFunc")
}
return nil
}
func alwaysError() error {
return someError
}
输出结果将是
2022/09/01 10:00:46 someFunc: something is wrong
有关详细信息,请参阅errors package。
英文:
It is possible to chain errors
package main
import (
"log"
"github.com/pkg/errors"
)
var someError = errors.New("something is wrong")
func main() {
// processing error on top level
if err := someFunc(); errors.Is(err, someError) {
log.Println(err)
}
}
func someFunc() error {
if err := alwaysError(); err != nil {
return errors.Wrap(err, "someFunc")
}
return nil
}
func alwaysError() error {
return someError
}
Output will be
2022/09/01 10:00:46 someFunc: something is wrong
See errors package for details
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论