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 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探