dscbxou1900343 2018-08-20 15:24
浏览 271
已采纳

如何检查errors.Errorf()中的类型错误?

Calls to string formatting functions like fmt.Printf seem to be a weak spot for the Go compiler. I end up with lots of bugs (using the wrong formatter after a refactor, forgetting to include all the arguments) that only reveal themselves at runtime. So I end up having to squint hard every time I write one of these.

I did some research today and discovered go tool vet, which appears to work for fmt.Printf, but it doesn't catch mistakes in errors.Errorf (see below).

import "github.com/pkg/errors"

func ReturnError(s string, i int) error {
    // Swap %d and %s, and forget to include the second argument
    return errors.Errorf("invalid arguments %d and %s", s)
}

Is there an analog to go tool vet that can capture string formatting errors in errors.Errorf()? Also, for my own understanding, why is this such a hard problem? It doesn't seem any more difficult for the Go compiler to catch string formatting type errors than any other kind of type errors.

  • 写回答

1条回答 默认 最新

  • dongqiao1964 2018-08-20 15:47
    关注

    You can tell go vet which functions to check for (compare godoc.org/cmd/vet):

    $ cat x.go
    package main
    
    import "github.com/pkg/errors"
    
    func ReturnError(s string, i int) error {
        // Swap %d and %s, and forget to include the second argument
        return errors.Errorf("invalid arguments %d and %s", s)
    }
    $ go vet x.go 
    $ go vet -printfuncs Errorf x.go 
    # command-line-arguments
    ./x.go:7: Errorf format %d has arg s of wrong type string
    

    It's not straightforward to do this better for a number of reasons:

    • Format strings are run-time values: You might well call fmt.Sprintf(prefix + "%s", ...). So it is impossible to catch all invalid format strings at compile time.
    • Format strings don't have a special type. Hence the compiler can't easily determine that some function (errors.Errorf in this case) expects its arguments to behave like fmt.Printf just by looking at the function definition.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?