
我正在 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
出现错误的原因是我希望能够为每个测试用例条目定义预期错误的列表。假设我知道为函数提供某些输入将使其沿着一条路径返回包含特定错误的错误。
新视窗企业管理系统是一款小巧、实用、利于后续开发的ASP程序。适合大中小型企业的网站建设。1、新闻管理 2、产品管理 3、订单管理 4、广告管理 5、下载管理 6、留言管理 8、单页栏目(如企业简介,资质荣誉)9、人才招聘等等。 新视窗企业管理系统 5.1 更新日志:1、修改产品列表的图片自动缩略,防止图片变形.2、修改后台添加产品分类时,排序ID不写入数据库的错误.3、修改首页企业简介的链接地址
如何将 *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。









