drnf09037160 2017-09-03 10:32
浏览 335
已采纳

在Go中返回nil或自定义错误

When using a custom Error type in Go (with extra fields to capture some details), when trying to return nil as value of this type, I get compile errors like cannot convert nil to type DetailedError or like cannot use nil as type DetailedError in return argument, from code looking mostly like this:

type DetailedError struct {
    x, y int
}

func (e DetailedError) Error() string {
    return fmt.Sprintf("Error occured at (%s,%s)", e.x, e.y)
}

func foo(answer, x, y int) (int, DetailedError) {
    if answer == 42 {
        return 100, nil  //!! cannot use nil as type DetailedError in return argument
    }
    return 0, DetailedError{x: x, y: y}
}

(full snippet: https://play.golang.org/p/4i6bmAIbRg)

What would be the idiomatic way to solve this problem? (Or any way that works...)

I actually need the extra fields on errors because I have detailed error messages constructed by complex logic from simpler ones etc., and if I would just fall back to "string errors" I'd basically have to parse those strings to pieces and have logic happen based on them and so on, which seems really ugly (I mean, why serialize to strings info you know you're gonna need to deserialize later...)

  • 写回答

2条回答 默认 最新

  • doucao1888 2017-09-03 11:11
    关注

    Don't use DetailedError as a return type, always use error:

    func foo(answer, x, y int) (int, error) {
        if answer == 42 {
            return 100, nil  //!! cannot use nil as type DetailedError in return argument
        }
        return 0, DetailedError{x: x, y: y}
    }
    

    The fact that your DetailedError type satisfies the error interface is sufficient to make this work. Then, in your caller, if you care about the extra fields, use a type assertion:

    value, err := foo(...)
    if err != nil {
        if detailedErr, ok := err.(DetailedError); ok {
            // Do something with the detailed error values
        } else {
            // It's some other error type, behave accordingly
        }
    }
    

    Reasons for not returning DetailedError:

    It may not appear to matter right now, but in the future your code may expand to include additional error checks:

    func foo(answer, x, y int) (int, error) {
        cache, err := fetchFromCache(answer, x, y)
        if err != nil {
            return 0, fmt.Errorf("Failed to read cache: %s", err)
        }
        // ... 
    }
    

    The additional error types won't be of DetailedError type, so you then must return error.

    Further, your method may be used by other callers that don't know or care about the DetailedError type:

    func fooWrapper(answer, x, y int) (int, error) {
        // Do something before calling foo
        result, err := foo(answer, x, y)
        if err != nil {
            return 0, err
        }
        // Do something after calling foo
        return result, nil
    }
    

    It's unreasonable to expect every caller of a function to understand a custom error type--this is precisely why interfaces, and in particular the error interface, exists in Go.

    Take advantage of this, don't circumvent it.

    Even if your code never changes, having a new custom error type for every function or use-case is unsustainable, and makes your code unreadable and impossible to reason about.

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

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。