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条)

报告相同问题?

悬赏问题

  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别