Elixir エラーハンドリングのパターン

存在しないファイルを読み込んだ時、:ok は帰ってこない為、パターンマッチに失敗してエラーとなる。

[bash]
iex(1)> {:ok, file} = File.read "non_exist_file.txt"
** (MatchError) no match of right hand side value: {:error, :enoent}
[/bash]

存在しないファイルを読み込んだ時、:error が帰ってくる為、パターンマッチに失敗しない。

[bash]
iex(2)> {:error, enoent} = File.read "non_exist_file.txt"
{:error, :enoent}
[/bash]

普通の言語なら、下記の2つの文をif文で制御するところだが、上記の制御を振り分けるためには、case文を使用するようだ。

[bash]
case File.read "non_exist_file.txt" do
{:ok, file} -> IO.puts "OK!!"
{:error, enoent} -> IO.puts "File not found Error!!"
end
[/bash]

中々、慣れない。

This entry was posted in Elixir, 技術情報. Bookmark the permalink.

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です