
我正在 go 中尝试错误包装,并有一个返回包装的自定义错误类型的函数。我想做的是迭代预期错误列表并测试函数的输出是否包含这些预期错误。
我发现将自定义错误放入 []error 意味着自定义错误的类型将为 *fmt.wraperror,这意味着 errors.as() 几乎总是返回 true。
作为示例,请考虑以下代码:
package main
import (
"errors"
"fmt"
)
type anothererror struct {
}
func (e *anothererror) error() string {
return "another error"
}
type missingattrerror struct {
missingattr string
}
func (e *missingattrerror) error() string {
return fmt.sprintf("missing attribute: %s", e.missingattr)
}
func dosomething() error {
e := &missingattrerror{missingattr: "key"}
return fmt.errorf("dosomething(): %w", e)
}
func main() {
err := dosomething()
expectederrone := &missingattrerror{}
expectederrtwo := &anothererror{}
expectederrs := []error{expectederrone, expectederrtwo}
fmt.printf("is err '%v' type '%t'?: %t\n", err, expectederrone, errors.as(err, &expectederrone))
fmt.printf("is err '%v' type '%t'?: %t\n", err, expectederrtwo, errors.as(err, &expectederrtwo))
for i := range expectederrs {
fmt.printf("is err '%v' type '%t'?: %t\n", err, expectederrs[i], errors.as(err, &expectederrs[i]))
}
}其输出为
is err 'dosomething(): missing attribute: key' type '*main.missingattrerror'?: true is err 'dosomething(): missing attribute: key' type '*main.anothererror'?: false is err 'dosomething(): missing attribute: key' type '*fmt.wraperror'?: true is err 'dosomething(): missing attribute: key' type '*fmt.wraperror'?: true
理想情况下我希望输出是
立即学习“go语言免费学习笔记(深入)”;
Is err 'DoSomething(): missing attribute: Key' type '*main.MissingAttrError'?: true Is err 'DoSomething(): missing attribute: Key' type '*main.AnotherError'?: false Is err 'DoSomething(): missing attribute: Key' type '*main.MissingAttrError'?: true Is err 'DoSomething(): missing attribute: Key' type '*main.AnotherError'?: false
出现错误的原因是我希望能够为每个测试用例条目定义预期错误的列表。假设我知道为函数提供某些输入将使其沿着一条路径返回包含特定错误的错误。
如何将 *fmt.wraperror 类型从 []error 切片转换回原始类型,以便我可以将其与 error.as 一起使用?
我知道我可以使用 将其强制转换为特定类型。(anothererror),但为了在迭代切片时使其工作,我必须对函数可能返回的每个可能的错误执行此操作,不是吗?)
您可以使用以下方法欺骗 errors.as:
func main() {
err := DoSomething()
m := &MissingAttrError{}
a := &AnotherError{}
expected := []any{&m, &a}
for i := range expected {
fmt.Printf("Is err '%v' type '%T'?: %t\n", err, expected[i], errors.As(err, expected[i]))
}
}打印的类型不是您所期望的,但 errors.as 按其应有的方式工作。
您的示例不起作用的原因是您传递给 errors.as 的是 *error。因此,包装的错误值(即 err)被直接分配给目标值。在我的示例中,传递给 errors.as 的值是 **anothererror,并且 err 不能分配给 *anothererror。
以上就是Golang 中具体类型的错误片段的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号