Go – errors.As 无法解包自定义错误类型

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

Go - errors.As failing to unwrap custom error type

问题

我正在尝试使用Go标准库中的errors包,使用errors.As来解包一个自定义的错误类型,但似乎检查失败,无法提取底层错误。

我提取了一个最小的可复现示例:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type myError struct {
  7. err error
  8. }
  9. func (m myError) Error() string {
  10. return fmt.Sprintf("my error: %s", m.err)
  11. }
  12. func retError() error {
  13. return &myError{errors.New("wrapped")}
  14. }
  15. func main() {
  16. var m myError
  17. if err := retError(); errors.As(err, &m) {
  18. fmt.Println("unwrapped", m.err)
  19. } else {
  20. fmt.Println(err)
  21. }
  22. }

https://go.dev/play/p/I7BNk4-rDIB - 这是在Go Playground上的示例。如果运行,它将打印出"my error: wrapped"而不是预期的"unwrapped wrapped"。

errors.As文档中的示例可以正常工作,我似乎无法理解我做错了什么 - 我将*myError传递给了errors.As,这似乎是正确的(因为将myError传递给它会引发恐慌:"目标必须是非nil指针",这是预期的行为)。

英文:

I'm trying to use the Go stdlib package errors to unwrap a custom error type using errors.As, however it seems as though the check is failing and I cannot extract the underlying error.

I've extracted a minimal reproducible example:

  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type myError struct {
  7. err error
  8. }
  9. func (m myError) Error() string {
  10. return fmt.Sprintf("my error: %s", m.err)
  11. }
  12. func retError() error {
  13. return &myError{errors.New("wrapped")}
  14. }
  15. func main() {
  16. var m myError
  17. if err := retError(); errors.As(err, &m) {
  18. fmt.Println("unwrapped", m.err)
  19. } else {
  20. fmt.Println(err)
  21. }
  22. }

https://go.dev/play/p/I7BNk4-rDIB - the example on the Go playground. If launched, it will print "my error: wrapped" instead of the expected "unwrapped wrapped".

The example from the errors.As documentation works, and I can't seem to understand what am I doing incorrectly - I'm passing a *myError to errors.As, which seems to be correct (since passing a myError raises a panic: target must be a non-nil pointer, which is expected).

答案1

得分: 0

将代码中的注释翻译为中文:

改为:

  1. func retError() error {
  2. return myError{errors.New("wrapped")}
  3. }
英文:

Instead of:

  1. func retError() error {
  2. return &myError{errors.New("wrapped")}
  3. }

Do:

  1. func retError() error {
  2. return myError{errors.New("wrapped")}
  3. }

huangapple
  • 本文由 发表于 2022年12月16日 03:26:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/74816590.html
匿名

发表评论

匿名网友

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

确定