gpt4 book ai didi

go - 检查来自 os.Remove 的错误消息

转载 作者:IT王子 更新时间:2023-10-29 01:40:53 27 4
gpt4 key购买 nike

检查错误消息最惯用的方法是什么?我的用例是在 err := os.Remove(path) 中,我认为是成功的:

A) 如果 err == nil

B) 如果 err != nil 但是由于找不到文件而抛出错误。

任何其他错误都会导致删除重试。目前我已经将其包装在 for { ... } 循环中并正在检查:

if err == nil || strings.Contains(err.Error(), "no such file") {
// Success
} else {
// Fail
}

the docs说:

If there is an error, it will be of type *PathError.

我不认为有一种方法可以通过类型断言来检查。我错过了一些基本的东西吗?我在 Go 中的错误处理总是感觉有些草率。

最佳答案

“类型”error 是一个接口(interface)。接口(interface)没有具体类型。要获取值的类型,您可以使用类型断言或类型开关:

// Type assertion
_, ok := err.(*PathError)

// Type switch
switch err.(type) {
case *PathError:
// You know the type now
}

这是找出错误类型的惯用方法。正如在指定的注释中,os 包中已经有一个函数可以为您执行此操作 (https://golang.org/pkg/os/#IsNotExist)

关于go - 检查来自 os.Remove 的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51736912/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com