Home > Enterprise >  Golang use of Zerolog and raising errors
Golang use of Zerolog and raising errors

Time:09-02

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?

CodePudding user response:

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

  • Related