LoginSignup
1
0

More than 1 year has passed since last update.

Fiber#raiseによって外部から発されたエラーをFiber内でrescueしてみる

Last updated at Posted at 2022-02-27

個人的なメモです。
趣味のrubyの非同期タスクスケジューラーの実装に必要になった。
自分で手を動かして挙動を見ておきたかっただけ。

公式ドキュメント

動作検証(エラーキャッチなし)

f = Fiber.new do
  Fiber.yield(:a)
  Fiber.yield(:b)
  Fiber.yield(:c)
  Fiber.yield(:d)
end

> p f.resume
# => :a

> f.raise StandardError.new("Fiber Interruption from #raise")
# in `yield': Fiber Interruption from #raise (StandardError)

> p f.resume
# attempt to resume a terminated fiber (FiberError)

動作検証(エラーキャッチあり)

f = Fiber.new do
  Fiber.yield(:a)
  begin
    Fiber.yield(:b)            ## 2回resumeした後にraiseしたらここでエラーが発される。
  rescue StandardError => e
    Fiber.yield e.message
  end
  Fiber.yield(:c)
  Fiber.yield(:d)
end

結果は以下。ちゃんとfiber内でrescueできた。
image.png

ドキュメントにある通り、

selfが表すファイバーが最後に Fiber.yield を呼んだ場所で例外を発生させます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0