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

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

Go - errors.As failing to unwrap custom error type

问题

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

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

package main

import (
	"errors"
	"fmt"
)

type myError struct {
	err error
}

func (m myError) Error() string {
	return fmt.Sprintf("my error: %s", m.err)
}

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

func main() {
	var m myError
	if err := retError(); errors.As(err, &m) {
		fmt.Println("unwrapped", m.err)
	} else {
		fmt.Println(err)
	}
}

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:

package main

import (
	"errors"
	"fmt"
)

type myError struct {
	err error
}

func (m myError) Error() string {
	return fmt.Sprintf("my error: %s", m.err)
}

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

func main() {
	var m myError
	if err := retError(); errors.As(err, &m) {
		fmt.Println("unwrapped", m.err)
	} else {
		fmt.Println(err)
	}
}

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

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

改为:

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

Instead of:

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

Do:

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

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:

确定