This is an archive of the discontinued LLVM Phabricator instance.

[Support] Add a free toString function for Error
ClosedPublic

Authored by vsk on May 3 2016, 11:28 AM.

Details

Summary
  1. Introduce a toString(Error) function which produces a error string.
  2. Add a message() method to ErrorInfoBase with a sensible default implementation.

This should help reduce code duplication and simplify porting code which uses std::error_code.

Diff Detail

Repository
rL LLVM

Event Timeline

vsk updated this revision to Diff 56036.May 3 2016, 11:28 AM
vsk retitled this revision from to [Support/Error] Add a string conversion method to Error.
vsk updated this object.
vsk added a reviewer: lhames.
vsk added a subscriber: llvm-commits.
lhames edited edge metadata.May 3 2016, 12:42 PM

Hrm. This particular plan sounded better in my head when we were discussing it earlier. My bad.

I like the idea of adding a message() method to ErrorInfoBase so that clients can write something like:

std::string Msg;
handle(std::move(Err),
  [&](ErrorInfoBase &E) {
    Msg = E.message();
  });

And I think it'd be useful to wrap all that up in a free function like 'toString', so that you could write:

std::string Msg = toString(std::move(Err));

However, unless there's a compelling reason not to, I think toString should consume the Error the same way logAllUnhandledErrors does.

The only reason I can think of not to consume the error (but still to log it) is for debugging output:

auto E = canFail(...);
DEBUG(OS << "canFail generated an error: " << toString(E) << "\n");
// ...
// Actually handle or return E.

If we want to support that idiom we should introduce non-consuming variants of both logAllUnhandled and toString for consistency.

vsk added a comment.May 3 2016, 1:00 PM

Lang and I discusses this off-list and reached the conclusion that it makes more sense to have a *destructive* toString operation on ErrorInfoBase (not Error).

That's because: 1) the whole point of Error is to enforce centralized error handling, and 2) the Error class should just handle ownership -- we already use ErrorInfoBase for log so message really belongs there.

Lang's example of a use-case for a non-destructive toString method is interesting but I haven't run into such a use case in practice. So, we can defer that until it's needed.

vsk updated this revision to Diff 56075.May 3 2016, 3:46 PM
vsk retitled this revision from [Support/Error] Add a string conversion method to Error to [Support] Add a free toString function for Error.
vsk updated this object.
vsk edited edge metadata.
  • Address Lang's review feedback.
lhames accepted this revision.May 3 2016, 4:22 PM
lhames edited edge metadata.

LGTM. Thanks Vedant. :)

This revision is now accepted and ready to land.May 3 2016, 4:22 PM
This revision was automatically updated to reflect the committed changes.