Go1.21 速览: panic(nil) 将成为历史!

306次阅读  |  发布于11月以前

使用panic返回错误、抛出异常

在 Go 语言中,返回错误、抛出异常一直是大家比较关注的话题。在抛出异常上,我们一般都是这么用的:

func mayPanic() {
    panic("脑子进煎鱼了")
}

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered. Error:\n", r)
            return
        }

        fmt.Println("煎鱼进脑子了")
    }()

    mayPanic()

    fmt.Println("After mayPanic()")
}

运行结果:

Recovered. Error:
 脑子进煎鱼了

这看起来一切正常,没什么问题的样子。

隐晦的雷

其实在现在的 Go 版本有一个较隐晦的雷。看看 panic 和 recover 对应的参数和返回类型。如下:

func panic(v interface{})
func recover() interface{}

参数值类型是 interface,也就意味着可以传任何值。那我们传 nil 给 panic 行不行呢?

如下代码:

func mayPanic() {
 panic(nil)
}

func main() {
 defer func() {
  if r := recover(); r != nil {
   fmt.Println("Recovered. Error:\n", r)
   return
  }

  fmt.Println("煎鱼进脑子了")
 }()

 mayPanic()

 fmt.Println("After mayPanic()")
}

再看一下输出结果,你认为是什么?

运行结果:煎鱼进脑子了。

虽然确实调用 panic(nil) 往里传了 nil 值。这结果说对好像也对,说不对好像也很怪?

因为我们触发了异常(panic),就是希望程序抛出异常,但却因为入参 “阴差阳错” 是 nil,这个应用程序就按正常逻辑走的。这显然和 panic 的语法特性预期不相符。

甚至社区有反馈,因为这一个坑,他们团队花了 3 个小时来排查:

还是有些隐晦的,不遇到的还真不一定知道。

修复 panic(nil)

这在 2018 年由 Go 的核心成员@ Brad Fitzpatrick 提出了《spec: guarantee non-nil return value from recover[1]》期望得到解决。

如下图:

其认为 panic(nil) 现在的处理是不正确的,应该要返回 runtime 错误,类似 runtime.NilPanic 的一个特殊类型。

经过 4-5 年的社区讨论、放置、纠结、处理后,将会在 Go1.21 起正式提供一个 PanicNilError 的新错误类型,用于替换和修复 panic(nil) 的场景。

PanicNilError 类型定义如下:

// A PanicNilError happens when code calls panic(nil).
//
// Before Go 1.21, programs that called panic(nil) observed recover returning nil.
// Starting in Go 1.21, programs that call panic(nil) observe recover returning a *PanicNilError.
// Programs can change back to the old behavior by setting GODEBUG=panicnil=1.
type PanicNilError struct {
 // This field makes PanicNilError structurally different from
 // any other struct in this package, and the _ makes it different
 // from any struct in other packages too.
 // This avoids any accidental conversions being possible
 // between this struct and some other struct sharing the same fields,
 // like happened in go.dev/issue/56603.
 _ [0]*PanicNilError
}

func (*PanicNilError) Error() string { return "panic called with nil argument" }
func (*PanicNilError) RuntimeError() {}

在新版本中,Go 应用程序调用 panic(nil) 将会在 Go 编译器中被替换成 panic(new(runtime.PanicNilError)),这一动作变更 Go1.20 及以前的行为。

在 Go1.21 起,调用 panic(nil) 的运行结果会变成:

panicked: panic called with nil argument

由于这一行为本身是破坏 Go1 兼容性保障的,因此 Go 团队提供了兼容措施,在 Go 编译时新增 GODEBUG=panicnil=1 标识,就可以确保与老版本行为一致。

总结

在 Go 语言中,panic 关键字本身的目标就是抛出异常,但早期设计上出现了一定的纰漏,使用 nil 可以让应用程序继续正常运行。

这也算一个比较常见的点了,和平时写业务代码一样。要确保边界值和特殊值的判断,这样才能确保代码的健壮性和异常处理与预期保持一致。

推荐阅读

参考资料

[1]spec: guarantee non-nil return value from recover: https://github.com/golang/go/issues/25448

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8