[PATCH] D19883: [Support/Error] Add a string conversion method to Error

Vedant Kumar via llvm-commits llvm-commits at lists.llvm.org
Tue May 3 11:28:41 PDT 2016


vsk created this revision.
vsk added a reviewer: lhames.
vsk added a subscriber: llvm-commits.

It would be convenient to expose a method from Error that (1) does basically the same thing as std::error_code::message(), and (2) has the same semantics as an Error -> bool conversion.

This lets clients avoid the following anti-patterns (while ensuring that failure states are actually handled):

```
Error E = ...;
logAllUnhandledErrors(std::move(E), errs(), "");
// Gah! E is no longer available for further processing.
```

```
Error E = ...;
std::string Msg;
{
  raw_string_ostream OS(Msg); // Can't use logAllUnhandledErrors if the output isn't a raw_ostream.
  handleAllErrors(std::move(E), [&OS](const ErrorInfoBase &EI) {
    EI.log(OS);
  });
}
Diag() << Msg; // E is no longer available.
```

It also makes porting code which uses std::error_code easier.

http://reviews.llvm.org/D19883

Files:
  include/llvm/Support/Error.h
  unittests/Support/ErrorTest.cpp

Index: unittests/Support/ErrorTest.cpp
===================================================================
--- unittests/Support/ErrorTest.cpp
+++ unittests/Support/ErrorTest.cpp
@@ -544,4 +544,13 @@
   }
 }
 
+// Test that error messages work.
+TEST(Error, ErrorMessage) {
+  EXPECT_EQ(Error::success().message().compare(""), 0);
+
+  auto E = make_error<CustomError>(0);
+  EXPECT_EQ(E.message().compare("CustomError { 0}"), 0);
+  consumeError(std::move(E));
+}
+
 } // end anon namespace
Index: include/llvm/Support/Error.h
===================================================================
--- include/llvm/Support/Error.h
+++ include/llvm/Support/Error.h
@@ -207,6 +207,20 @@
     return getPtr() && getPtr()->isA(ErrT::classID());
   }
 
+  /// Get the error message. Uses the log method on all contained instances of
+  /// ErrorInfoBase if this Error is in a failure state, and the empty string
+  /// if the error is in a Success state. This has the same effect on the
+  /// underlying Error as a bool conversion.
+  std::string message() {
+    this->operator bool();
+    std::string Msg;
+    if (getPtr()) {
+      raw_string_ostream OS(Msg);
+      getPtr()->log(OS);
+    }
+    return Msg;
+  }
+
 private:
   void assertIsChecked() {
 #ifndef NDEBUG


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D19883.56036.patch
Type: text/x-patch
Size: 1270 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20160503/3934a654/attachment.bin>


More information about the llvm-commits mailing list