Golang使用Zerolog和引发错误

huangapple go评论103阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年9月1日 08:21:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/73563136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定