[Support] Add ExitOnError utility to support tools that use the exit-on-error
authorLang Hames <lhames@gmail.com>
Thu, 17 Mar 2016 21:28:49 +0000 (21:28 +0000)
committerLang Hames <lhames@gmail.com>
Thu, 17 Mar 2016 21:28:49 +0000 (21:28 +0000)
commit6935c2d3227661bda111bdecae976a091b8307d8
tree936675c00ce2c608a996488e45ba4bda358108f2
parent016b2d0ddc4855a2e07161abd9ba6cdcebadd0c4
[Support] Add ExitOnError utility to support tools that use the exit-on-error
idiom.

Most LLVM tool code exits immediately when an error is encountered and prints an
error message to stderr. The ExitOnError class supports this by providing two
call operators - one for Errors, and one for Expected<T>s. Calls to code that
can return Errors (or Expected<T>s) can use these calls to bail out on error,
and otherwise continue as if the operation had succeeded. E.g.

Error foo();
Expected<int> bar();

int main(int argc, char *argv[]) {
  ExitOnError ExitOnErr;

  ExitOnErr.setBanner(std::string("Error in ") + argv[0] + ":");

  // Exit if foo returns an error. No need to manually check error return.
  ExitOnErr(foo());

  // Exit if bar returns an error, otherwise unwrap the contained int and
  // continue.
  int X = ExitOnErr(bar());

  // ...

  return 0;
}

llvm-svn: 263749
llvm/include/llvm/Support/Error.h
llvm/unittests/Support/ErrorTest.cpp