Adding useful error message for File
authorTom Jackson <tjackson@fb.com>
Mon, 4 Mar 2013 19:52:58 +0000 (11:52 -0800)
committerJordan DeLong <jdelong@fb.com>
Tue, 19 Mar 2013 00:08:05 +0000 (17:08 -0700)
Summary:
'open() failed' isn't too helpful. Seeing a filename there is. So I
added it.

Test Plan: Unit test

Reviewed By: mohittalwar@fb.com

FB internal diff: D725204

folly/File.cpp
folly/test/FileTest.cpp

index b2f8900e11f408d59f2054379a5cebb7ad169981..1262dd1c3aaedab8616e2d45d19a9c1267147c02 100644 (file)
@@ -15,6 +15,7 @@
  */
 
 #include "folly/File.h"
+#include "folly/Format.h"
 #include "folly/ScopeGuard.h"
 
 #include <system_error>
@@ -38,7 +39,9 @@ File::File(const char* name, int flags, mode_t mode)
   , ownsFd_(false) {
 
   if (fd_ < 0) {
-    throw std::system_error(errno, std::system_category(), "open() failed");
+    throw std::system_error(errno, std::system_category(),
+                            folly::format("open(\"{}\", {:#o}, 0{:#o}) failed",
+                                          name, flags, mode).str());
   }
   ownsFd_ = true;
 }
index 0111e4b97f5f514922fa8891d8f493ff4993224f..14b027c98bb2d6cdceaa63b4ab617a0773c1819a 100644 (file)
@@ -84,3 +84,15 @@ TEST(File, OwnsFd) {
   ::close(p[0]);
 }
 
+#define EXPECT_CONTAINS(haystack, needle) \
+  EXPECT_NE(::std::string::npos, ::folly::StringPiece(haystack).find(needle)) \
+    << "Haystack: '" << haystack << "'\nNeedle: '" << needle << "'";
+
+TEST(File, UsefulError) {
+  try {
+    File("does_not_exist.txt", 0, 0666);
+  } catch (const std::runtime_error& e) {
+    EXPECT_CONTAINS(e.what(), "does_not_exist.txt");
+    EXPECT_CONTAINS(e.what(), "0666");
+  }
+}