Avoid checking if error is nil repetition?

前端 未结 6 2201
无人及你
无人及你 2021-01-30 03:50

I\'m currently learning go and some of my code looks like this:

a, err := doA()
if err != nil {
  return nil, err
}
b, err := doB(a)
if err != nil {
  return nil         


        
6条回答
  •  不知归路
    2021-01-30 04:20

    If you have many of such re-occurring situations where you have several of these error checks you may define yourself a utility function like the following:

    func validError(errs ...error) error {
        for i, _ := range errs {
            if errs[i] != nil {
                return errs[i]
            }
        }
        return nil
    }
    

    This enables you to select one of the errors and return if there is one which is non-nil.

    Example usage (full version on play):

    x, err1 := doSomething(2)
    y, err2 := doSomething(3)
    
    if e := validError(err1, err2); e != nil {
        return e
    }
    

    Of course, this can be only applied if the functions do not depend on each other but this is a general precondition of summarizing error handling.

提交回复
热议问题