module Errno

当操作系统遇到错误时,它通常会将错误报告为一个整数错误代码。

$ ls nosuch.txt
ls: cannot access 'nosuch.txt': No such file or directory
$ echo $? # Code for last error.
2

当 Ruby 解释器与操作系统交互并接收到这样的错误代码(例如 2)时,它会将该代码映射到一个特定的 Ruby 异常类(例如 Errno::ENOENT)。

File.open('nosuch.txt')
# => No such file or directory @ rb_sysopen - nosuch.txt (Errno::ENOENT)

每个此类都

因此

Errno::ENOENT.superclass # => SystemCallError
Errno::ENOENT::Errno     # => 2

嵌套类的名称可以通过方法 Errno.constants 获取。

Errno.constants.size         # => 158
Errno.constants.sort.take(5) # => [:E2BIG, :EACCES, :EADDRINUSE, :EADDRNOTAVAIL, :EADV]

如上所示,与每个类关联的错误代码可以作为常量的值获取;特定类的值在不同操作系统上可能有所不同。如果某个类在特定操作系统上不需要,则其值为零。

Errno::ENOENT::Errno      # => 2
Errno::ENOTCAPABLE::Errno # => 0

Errno 中的每个类都可以使用可选的消息进行创建。

Errno::EPIPE.new                  # => #<Errno::EPIPE: Broken pipe>
Errno::EPIPE.new("foo")           # => #<Errno::EPIPE: Broken pipe - foo>
Errno::EPIPE.new("foo", "here")   # => #<Errno::EPIPE: Broken pipe @ here - foo>

请参阅 SystemCallError.new