duanchouyi6730 2013-03-17 14:48
浏览 69
已采纳

Go中的自定义错误处理

I've been reading this blog post but I'm still not convinced I know exactly what to do to get custom errors that I can return from my functions and handle outside of them.

This is what I'm currently doing:

func doSomething() int {
    x := 0
    // Do something with x.
    ...
    if somethingBadHappened {
        return -1
    }
    if somethingElseBadHappened {
        return -2
    }
    return x
}

This is what I'd like to be doing:

func doSomething() int, ? {
    ...
    if somethingBadHappened {
        return ?, err
    }
    if somethingElseBadHappened {
        return ?, err2
    }
    return x, nil
}

But I'm not exactly sure how, and what to replace those question marks with.

  • 写回答

2条回答 默认 最新

  • dopr25398 2013-03-17 15:31
    关注

    I would turn

    func doSomething() int, ? {
            ...
            if somethingBadHappened {
                    return ?, err
            }
    
            if somethingElseBadHappened {
                    return ?, err2
            }
    
            return x, nil
    }
    

    into

    func doSomething() (r int, err error) {
    
            ...
    
            if somethingBadHappened {
                    err  = err1 // Whatever satisfies the `error` interface
                    return
            }
    
            if somethingElseBadHappened {
                    err = err2 // dtto
                    return
            }
    
            return x, nil
    }
    

    IOW, at the call site it is idiomatic* to ignore, never use or rely on, any other returned value if err != nil, so just don't care if r above has had been assigned some intermediate value or not.

    (*) In the first approximatiom, i.e. if not stated otherwise. E.g. an io.Reader explicitly declares it can return both err == io.EOF and valid data at the same time:

    When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF regardless.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)