我正在 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
理想情况下我希望输出是
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)
,但为了在迭代切片时使其工作,我必须对函数可能返回的每个可能的错误执行此操作,不是吗?) 将其强制转换为特定类型。(anothererror)
,但为了在迭代切片时使其工作,我必须对函数可能返回的每个可能的错误执行此操作,不是吗?)
正确答案
您可以使用以下方法欺骗 errors.as
正确答案
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
的是 *error
。因此,包装的错误值(即 err
)被直接分配给目标值。在我的示例中,传递给 errors.as
的值是 **anothererror
,并且 err
不能分配给 *anothererror
打印的类型不是您所期望的,但 按其应有的方式工作。🎜
🎜您的示例不起作用的原因是您传递给 🎜 的是 *error
。因此,包装的错误值(即 err
)被直接分配给目标值。在我的示例中,传递给 🎜 的值是 **anothererror
,并且 err
不能分配给 *anothererror
。🎜以上是Golang 中具体类型的错误片段的详细内容。更多信息请关注PHP中文网其他相关文章!

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

go'serrorhandlingurturnserrorsasvalues,与Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

AnefactiveInterfaceoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForeabStractionTosWapImplementations withCallingCallingCode.3)

集中式错误处理在Go语言中可以提升代码的可读性和可维护性。其实现方式和优势包括:1.将错误处理逻辑从业务逻辑中分离,简化代码。2.通过集中处理错误,确保错误处理的一致性。3.使用defer和recover来捕获和处理panic,增强程序健壮性。

Ingo,替代词Inivuntionsionializatializatializationfunctionsandsingletons.1)customInitializationfunctions hallowexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssementializatizatupsetups.2)单次固定元素限制ininconinconcurrent

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go语言的错误处理通过errors.Is和errors.As函数变得更加灵活和可读。1.errors.Is用于检查错误是否与指定错误相同,适用于错误链的处理。2.errors.As不仅能检查错误类型,还能将错误转换为具体类型,方便提取错误信息。使用这些函数可以简化错误处理逻辑,但需注意错误链的正确传递和避免过度依赖以防代码复杂化。

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3汉化版
中文版,非常好用

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。