Permalink
Browse files

Add File.read! that raises an exception with a descriptive message

  • Loading branch information...
1 parent fe7bb7c commit f270ee41a8de06db5b6ede264c55a5f8164335a5 @rafaelfranca rafaelfranca committed Mar 14, 2012
Showing with 31 additions and 0 deletions.
  1. +21 −0 lib/file.ex
  2. +10 −0 test/elixir/file_test.exs
View
@@ -1,3 +1,9 @@
+defexception File::Exception, reason: nil, action: "", path: nil do
+ def message(exception) do
+ "could not " <> exception.action <> " " <> exception.path <> ": " <> list_to_binary(:file.format_error(exception.reason))
+ end
+end
+
defmodule File do
require Erlang.file, as: F
require Erlang.filename, as: FN
@@ -89,6 +95,21 @@ defmodule File do
F.read_file(filename)
end
+ @doc """
+ Returns `binary`, where `binary` is a binary data object that contains the contents
+ of `filename`, or raises a `File::Exception` if an error occurs.
+ """
+ def read!(filename) do
+ result = read(filename)
+
+ case result do
+ match: { :ok, binary }
+ binary
+ match: { :error, reason }
+ raise Exception, reason: reason, action: "read file", path: filename
+ end
+ end
+
@doc """
Returns a list with the path splitted by the path separator. If an empty string
is given, then it returns the root path.
View
@@ -52,4 +52,14 @@ defmodule FileTest do
assert_match { :error, :enoent }, File.read(File.expand_path('../../fixtures/missing.txt', __FILE__))
end
+
+ test :read! do
+ assert_equal "FOO\n", File.read!(File.expand_path('../../fixtures/foo.txt', __FILE__))
+
+ expected_message = "could not read file fixtures/missing.txt: no such file or directory"
+
+ assert_raises File::Exception, expected_message, fn ->
+ File.read!("fixtures/missing.txt")
+ end
+ end
end

0 comments on commit f270ee4

Please sign in to comment.