如何检查由于磁盘空间不足导致写入失败的情况。

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

golang: how to check if a write fails due to insufficient disk space

问题

如果一个 Go 程序使用 Write() 返回错误,它会返回类似以下的内容:

write failed(*fs.PathError): write mnt/test.dat: no space left on device

除了字符串匹配外,是否有其他方法可以判断 PathError 是由于磁盘空间不足引起的?

注意:我正在使用 Linux,并且不关心在 Windows 上的工作原理。

英文:

If a go program return error with Write(), it returns something like this:

write failed(*fs.PathError): write mnt/test.dat: no space left on device

Is there anyway other than string matching for 'no space left on device', to know that a PathError is due to insufficient disk space?

Note: I am using Linux, and not caring about how it works on Windows.

答案1

得分: 1

是的,它可能对您编译的操作系统敏感,但您可以检查错误是否包装了syscall.ENOSPC

_, err := file.Write(stuff)
if err != nil {
    if errors.Is(err, syscall.ENOSPC) {
        // 设备上没有剩余空间
        return "获取更多空间"
    }
    // 其他错误
}
英文:

Yes, it may be sensitive to the OS you compile for but you can check if the error wraps syscall.ENOSPC.

_, err := file.Write(stuff)
if err != nil {
    if errors.Is(err, syscall.ENOSPC) {
        // There was no space left on the device
        return "get more space"
    }
    // something else is wrong
}

答案2

得分: 0

除了字符串匹配之外,还有其他方法可以判断PathError是否由磁盘空间不足引起吗?

英文:

> Is there anyway other than string matching for 'no space left on device', to know that a PathError is due to insufficient disk space?

No.

huangapple
  • 本文由 发表于 2021年11月15日 15:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/69970851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定