将 panic 捕获到字符串变量中。

huangapple go评论85阅读模式
英文:

capture panic into string variable

问题

我有一个不寻常的请求。我需要一种将我捕获的 panic 转换为字符串的方法,以便我可以保存它。我使用 recover() 捕获了 panic,但它无法转换为字符串,因为它是一个 runtime.boundError 类型的接口。有人知道如何将 panic 保存到字符串变量中以供将来使用吗?

英文:

I have an unusual request. I need a way to convert the panic that I captured to string so I can save it. I have captured panic with recover() but it can't be converted to string because it is an interface that is runtime.boundError type. Does anyone know how can I save panics into string var for future use?

答案1

得分: 1

我认为你可以使用类型断言。使用类型断言,你可以检查一个接口(在这种情况下是runtime.BoundError)是否是特定类型的。通常用于确保接口值满足另一个接口或找到接口的具体类型。

你可以查看这个示例代码,将其断言为string类型。
https://go.dev/play/p/b6EtGrh0gGj

英文:

I think you can use type assertion . using type assertion you can check if an interface (in this case runtime.BoundError as you said) is of a specific type .
and it is generally used to make sure that an interface value satisfies another interface or to find the concrete type of the interface.

check this playground . you can assert it into string type .
https://go.dev/play/p/b6EtGrh0gGj

huangapple
  • 本文由 发表于 2022年9月13日 15:44:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/73699229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定