Abstract

LEAF is a lightweight error handling library for C++11. Features:

  • Efficient delivery of arbitrary error objects to the correct error-handling scope.

  • No dynamic memory allocations.

  • Compatible with std::error_code, errno and any other error code type.

  • Can be used with or without exception handling.

  • Support for multi-thread programming.

Introduction | Tutorial | Synopsis | Whitepaper | Benchmark

Reference: Functions | Types | Traits | Macros

LEAF is designed with a strong bias towards the common use case where callers of functions which may fail check for success and forward errors up the call chain but do not handle them. When a function fails, the only data transported in the leaf::result<T> object is a simple discriminant. In this case, LEAF does not bother to make the actual error object(s) available to the caller. This saves a lot of cycles and results in very efficient code.

If the caller wants to handle at least some failures, this intention must be explicitly expressed by a call to try_handle_some. This instructs LEAF to deliver relevant error objects to this scope, so the program can inspect them and possibly restore normal operation. If we want to handle all, rather than only some failures, this is expressed by a call to try_handle_all. In this case, LEAF ensures (statically, at compile time) that the user provides suitable handlers for all failures.

Regardless of whether we call try_handle_some, try_handle_all, or the exception-handling alternative try_catch, LEAF reserves memory on the stack, suitable for storage of error objects based on the static types of the arguments of the provided error handlers. No dynamic memory allocations occur, even when working with extremely large error objects.

Five Minute Introduction

We’ll implement two versions of the same simple program: one using error codes to handle errors, and one using exception handling.

Using result<T>

We’ll write a short but complete program that reads a text file in a buffer and prints it to std::cout, using LEAF to handle errors without exception handling.

Let’s jump ahead and start with the main function: it will try several operations as needed and handle all the errors that occur. Did I say all the errors? I did, so we’ll use leaf::try_handle_all. It has the following signature:

template <class TryBlock, class... Handler>
<<deduced-type>> try_handle_all( TryBlock && try_block, Handler && ... handler );

TryBlock is a function type, almost always a lambda. It is required to return a result<T> type — for example, leaf::result<T> — that holds a value of type T or else it indicates a failure.

The first thing try_handle_all does is invoke the try_block function. If the returned object r indicates success, try_handle_all returns the contained r.value(); otherwise it calls the first suitable error handling function from the handler…​ list.

We’ll see later just what kind of a TryBlock will our main function pass to try_handle_all, but first, let’s look at the juicy error-handling part. LEAF will consider each of the handler…​ lambdas, in order, and call the first suitable match:

int main( int argc, char const * argv[] )
{
  return leaf::try_handle_all(

    [&]() -> leaf::result<int>
    {
      // The TryBlock code goes here, we'll see it later
    },

    [](leaf::match<error_code, input_file_open_error>, (1)
        leaf::match<leaf::e_errno, ENOENT>,
        leaf::e_file_name const & fn)
    {
      std::cerr << "File not found: " << fn.value << std::endl;
      return 1;
    },

    [](leaf::match<error_code, input_file_open_error>, (2)
        leaf::e_errno const & errn,
        leaf::e_file_name const & fn)
    {
      std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl;
      return 2;
    },

    [](leaf::match<error_code, input_file_size_error, input_file_read_error, input_eof_error>, (3)
        leaf::e_errno const & errn,
        leaf::e_file_name const & fn)
    {
      std::cerr << "Failed to access " << fn.value << ", errno=" << errn << std::endl;
      return 3;
    },

    [](leaf::match<error_code, cout_error>, (4)
        leaf::e_errno const & errn)
    {
      std::cerr << "Output error, errno=" << errn << std::endl;
      return 4;
    },

    [](leaf::match<error_code, bad_command_line>) (5)
    {
      std::cout << "Bad command line argument" << std::endl;
      return 5;
    },

    [](leaf::error_info const & unmatched) (6)
    {
      std::cerr <<
        "Unknown failure detected" << std::endl <<
        "Cryptic diagnostic information follows" << std::endl <<
        unmatched;
      return 6;
    }
  );
}
1 This handler will be called if the detected error includes:
• an object of type enum error_code equal to the value input_file_open_error, and
• an object of type leaf::e_errno that has .value equal to ENOENT, and
• an object of type leaf::e_file_name.
2 This handler will be called if the detected error includes:
• an object of type enum error_code equal to input_file_open_error, and
• an object of type leaf::e_errno (regardless of its .value), and
• an object of type leaf::e_file_name.
3 This handler will be called if the detected error includes:
• an object of type enum error_code equal to any of input_file_size_error, input_file_read_error, input_eof_error, and
• an object of type leaf::e_errno (regardless of its .value), and
• an object of type leaf::e_file_name.
4 This handler will be called if the detected error includes:
• an object of type enum error_code equal to cout_error, and
• an object of type leaf::e_errno (regardless of its .value),
5 This handler will be called if the detected error includes an object of type enum error_code equal to bad_command_line.
6 This last handler is a catch-all for any error, in case no other handler could be matched: it prints diagnostic information to help debug logic errors in the program, since it failed to match an appropriate error handler to the error condition it encountered.

Now, reading and printing a file may not seem like a complex job, but let’s split it into several functions, each communicating failures using leaf::result<T>:

//Parse the command line, return the file name.
leaf::result<char const *> parse_command_line( int argc, char const * argv[] );

//Open a file for reading.
leaf::result<std::shared_ptr<FILE>> file_open( char const * file_name );

//Return the size of the file.
leaf::result<int> file_size( FILE & f );

//Read size bytes from f into buf.
leaf::result<void> file_read( FILE & f, void * buf, int size );

For example, let’s look at file_open:

leaf::result<std::shared_ptr<FILE>> file_open( char const * file_name )
{
  if( FILE * f = fopen(file_name,"rb") )
    return std::shared_ptr<FILE>(f,&fclose);
  else
    return leaf::new_error( input_file_open_error, leaf::e_errno{errno} );
}

If fopen succeeds, we return a shared_ptr which will automatically call fclose as needed. If fopen fails, we report an error by calling new_error, which takes any number of error objects to load with the error. In this case we pass the system errno (LEAF defines struct e_errno {int value;}), and our own error code value, input_file_open_error.

Here is our complete error code enum:

enum error_code
{
  bad_command_line = 1,
  input_file_open_error,
  input_file_size_error,
  input_file_read_error,
  input_eof_error,
  cout_error
};

Looks good, but how does LEAF know that this enum represents error codes and not, say, types of cold cuts sold at Bay Cities Italian Deli? It doesn’t, unless we tell it:

namespace boost { namespace leaf {

  template<> struct is_e_type<error_code>: std::true_type { };

} }

We’re now ready to look at the TryBlock we’ll pass to try_handle_all. It does all the work, bails out if it encounters an error:

int main( int argc, char const * argv[] )
{
  return leaf::try_handle_all(

    [&]() -> leaf::result<int>
    {
      leaf::result<char const *> file_name = parse_command_line(argc,argv);
      if( !file_name )
        return file_name.error();

Wait, what’s this, if "error" return "error"? There is a better way: we’ll use LEAF_AUTO. It takes a result<T> and bails out in case of a failure (control leaves the calling function), otherwise defines a local variable to access the T value stored in the result object.

This is what our TryBlock really looks like:

int main( int argc, char const * argv[] )
{
  return leaf::try_handle_all(

    [&]() -> leaf::result<int> (1)
    {
      LEAF_AUTO(file_name, parse_command_line(argc,argv)); (2)

      auto load = leaf::preload( leaf::e_file_name{file_name} ); (3)

      LEAF_AUTO(f, file_open(file_name)); (4)

      LEAF_AUTO(s, file_size(*f)); (4)

      std::string buffer( 1 + s, '\0' );
      LEAF_CHECK(file_read(*f, &buffer[0], buffer.size()-1)); (4)

      std::cout << buffer;
      std::cout.flush();
      if( std::cout.fail() ) (5)
        return leaf::new_error( cout_error, leaf::e_errno{errno} );

      return 0;
    },

    .... // The list of error handlers goes here

  ); (6)
}
1 Our TryBlock returns a result<int>. In case of success, it will hold 0, which will be returned from main to the OS.
2 If parse_command_line returns an error, we forward that error to try_handle_all (which invoked us) verbatim. Otherwise, LEAF_AUTO gets us a local variable file_name to access the char const * result.
3 From now on, all errors escaping this scope will automatically communicate the (now successfully parsed from the command line) file name (LEAF defines struct e_file_name {std::string value;}). It’s as if every time one of the following functions wants to report an error, preload says "wait, associate this e_file_name object with the error, it’s important!"
4 Call more functions, forward each failure to the caller…​
5 …​but this is slightly different: we didn’t get a failure via result<T> from another function, this is our own error we’ve detected! We return a new_error, passing the cout_error error code and the system errno (LEAF defines struct e_errno {int value;}).
6 This concludes the try_handle_all arguments — as well as our program!

Nice and simple! Writing the TryBlock, we focus on the "no errors" code path — if we encounter any error we just return it to try_handle_all for processing. Well, that’s if we’re being good and using RAII for automatic clean-up — which we are, shared_ptr will automatically close the file for us.

The complete program from this tutorial is available here. The other version of the same program uses exception handling to report errors (see below).

Using Exception Handling

And now, we’ll write the same program that reads a text file in a buffer and prints it to std::cout, this time using exceptions to report errors. First, we need to define our exception class hierarchy:

struct print_file_error : virtual std::exception { };
struct command_line_error : virtual print_file_error { };
struct bad_command_line : virtual command_line_error { };
struct input_error : virtual print_file_error { };
struct input_file_error : virtual input_error { };
struct input_file_open_error : virtual input_file_error { };
struct input_file_size_error : virtual input_file_error { };
struct input_file_read_error : virtual input_file_error { };
struct input_eof_error : virtual input_file_error { };
To avoid ambiguities in the dynamic type conversion which occur when catching a base type, it is generally recommended to use virtual inheritance in exception type hierarchies.

Again, we’ll split the job into several functions, this time communicating failures by throwing exceptions (and, therefore, we do not need to use a result<T> type):

//Parse the command line, return the file name.
char const * parse_command_line( int argc, char const * argv[] );

//Open a file for reading.
std::shared_ptr<FILE> file_open( char const * file_name );

//Return the size of the file.
int file_size( FILE & f );

//Read size bytes from f into buf.
void file_read( FILE & f, void * buf, int size );

The main function brings everything together and handles all the exceptions that are thrown, but instead of using try and catch, it will use the function template leaf::try_catch, which has the following signature:

template <class TryBlock, class... Handler>
<<deduced-type>> try_catch( TryBlock && try_block, Handler && ... handler );

TryBlock is a function type, almost always a lambda; try_catch simply returns the value returned by the try_block, catching any exception it throws, in which case it calls the first suitable error handling function from the handler…​ list.

Let’s look at the TryBlock our main function passes to try_catch:

int main( int argc, char const * argv[] )
{
  std::cout.exceptions(std::ostream::failbit | std::ostream::badbit); (1)

  return leaf::try_catch(

    [&] (2)
    {
      char const * file_name = parse_command_line(argc,argv); (3)

      auto load = leaf::preload( leaf::e_file_name{file_name} ); (4)

      std::shared_ptr<FILE> f = file_open( file_name ); (3)

      std::string buffer( 1+file_size(*f), '\0' ); (3)
      file_read(*f,&buffer[0],buffer.size()-1); (3)

      auto propagate2 = leaf::defer([] { return leaf::e_errno{errno}; } ); (5)
      std::cout << buffer;
      std::cout.flush();

      return 0;
    },

    .... (6)

  ); (7)
}
1 Configure std::cout to throw on error.
2 Except if it throws, our TryBlock returns 0, which will be returned from main to the OS.
3 If any of the functions we call throws, try_catch will find an appropriate handler to invoke. We’ll look at that later.
4 From now on, all exceptions escaping this scope will automatically communicate the (now successfully parsed from the command line) file name (LEAF defines struct e_file_name {std::string value;}). It’s as if every time one of the following functions wants to throw an exception, preload says "wait, associate this e_file_name object with the exception, it’s important!"
5 defer is similar to preload, but instead of the error object, it takes a function that returns it. From this point on, if an exception escapes this scope, defer will call the passed function and load the returned e_errno with the exception (LEAF defines struct e_errno {int value;}).
6 List of error handlers goes here. We’ll see that later.
7 This concludes the try_catch arguments — as well as our program!

As it is always the case when using exception handling, as long as our TryBlock is exception-safe, we can focus on the "no errors" code path. Of course, our TryBlock is exception-safe, since shared_ptr will automatically close the file for us in case an exception is thrown.

Now let’s look at the second part of the call to try_catch, which lists the error handlers:

int main( int argc, char const * argv[] )
{
  std::cout.exceptions(std::ostream::failbit | std::ostream::badbit); (1)

  return leaf::try_catch(
    [&]
    {
      .... (2)
    },

    [](leaf::catch_<input_file_open_error>, (3)
        leaf::match<leaf::e_errno,ENOENT>,
        leaf::e_file_name const & fn)
    {
      std::cerr << "File not found: " << fn.value << std::endl;
      return 1;
    },

    [](leaf::catch_<input_file_open_error>, (4)
        leaf::e_errno const & errn,
        leaf::e_file_name const & fn )
    {
      std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl;
      return 2;
    },

    [](leaf::catch_<input_error>, (5)
        leaf::e_errno const & errn,
        leaf::e_file_name const & fn )
    {
      std::cerr << "Failed to access " << fn.value << ", errno=" << errn << std::endl;
      return 3;
    },

    [](leaf::catch_<std::ostream::failure>, (6)
        leaf::e_errno const & errn )
    {
      std::cerr << "Output error, errno=" << errn << std::endl;
      return 4;
    },

    [](leaf::catch_<bad_command_line>) (7)
    {
      std::cout << "Bad command line argument" << std::endl;
      return 5;
    },

    [](leaf::error_info const & unmatched) (8)
    {
      std::cerr <<
        "Unknown failure detected" << std::endl <<
        "Cryptic diagnostic information follows" << std::endl <<
        unmatched;
      return 6;
    } );
}
1 Configure std::cout to throw on error.
2 This is the TryBlock from the previous listing; if it throws, try_catch will catch the exception, then consider the error handlers that follow, in order, and it will call the first one that can deal with the error:
3 This handler will be called if:
• an input_file_open_error exception was caught, with
• an object of type leaf::e_errno that has .value equal to ENOENT, and
• an object of type leaf::e_file_name.
4 This handler will be called if:
• an input_file_open_error exception was caught, with
• an object of type leaf::e_errno (regardless of its .value), and
• an object of type leaf::e_file_name.
5 This handler will be called if:
• an input_error exception was caught (which is a base type), with
• an object of type leaf::e_errno (regardless of its .value), and
• an object of type leaf::e_file_name.
6 This handler will be called if:
• an std::ostream::failure exception was caught, with
• an object of type leaf::e_errno (regardless of its .value),
7 This handler will be called if a bad_command_line exception was caught.
8 If try_catch fails to find an appropriate handler, it will re-throw the exception. But this is the main function which should handle all exceptions, so this last handler matches any error and prints diagnostic information, to help debug logic errors.

To conclude this introduction, let’s look at one of the error-reporting functions that our TryBlock calls, for example file_open:

std::shared_ptr<FILE> file_open( char const * file_name )
{
  if( FILE * f = fopen(file_name,"rb") )
    return std::shared_ptr<FILE>(f,&fclose);
  else
    throw leaf::exception( input_file_open_error(), leaf::e_errno{errno} );
}

If fopen succeeds, it returns a shared_ptr which will automatically call fclose as needed. If fopen fails, we throw the exception object returned by leaf::exception, which takes as its first argument an exception object, followed by any number of error objects to load with it. In this case we pass the system errno (LEAF defines struct e_errno {int value;}). The returned object can be caught as input_file_open_error.

try_catch works with any exception, not only exceptions thrown using leaf::exception.
The complete program from this tutorial is available here. The other version of the same program does not use exception handling to report errors (see the previous introduction).

Tutorial

Definitions

The following terms are used throughout this documentation:

Error types, or E-types:

User-defined value types that describe or pertain to a failure. Objects of these types may carry std::error_code, error enums, relevant file names, and any other information that is required by an error-handling scope in case of a failure. E-types must define no-throw move, but need not be copyable.

error_id:

This is a value type that acts as a program-wide unique identifier of a particular occurrence of a failure. It is as efficient as an int. In addition the error_id type is implicitly convertible to std::error_code. This enables LEAF error IDs to be communicated through any compatible API in plain std::error_code objects, which LEAF recognizes by its own specific std::error_category.

context<E…​>:

A context is an associative container of E-types, which it stores statically in a std::tuple. A context object may store at most a single object of each of the E…​ types. When an E-object is stored in a context, it is always associated with a specific error_id value. Typically, context objects are local to the try_handle_some, try_handle_all or try_catch function invoked by an error-handling scope.

Error-initiating function:

A function that detects and reports a new failure. Usually such functions call new_error to generate a new error_id for each error condition they encounter; typically, at least one E-object is associated with the new error_id at this point.

Error-neutral function:

A function which, in case a lower level function fails, forwards the reported error to its caller, possibly associating additional E-objects with it.

Error-handling function:

A function that recognizes and recovers from at least some errors reported by lower level functions. Error-handling functions typically call try_handle_some, try_handle_all or try_catch, passing a list of handlers.

Handler:

A function (almost always a lambda), which is able to handle a specific error condition identified by its arguments (usually of E-types). In typical use, if a low-level function attempts to communicate an E-object, it is discarded unless at least one error-handling scope up the call chain contains a handler that takes an argument of that E-type.

Scopes that handle errors require an error_id and a list of handlers, which they typically pass to try_handle_some, try_handle_all or try_catch. The error_id is transported in one of the following ways:

To handle an error, LEAF calls the first of the specified handlers whose arguments can be supplied by the E-objects loaded in a local context that are associated with the delivered error_id.


Error Communication Model

Using noexcept Functionality

The following figure illustrates how error objects are transported when using LEAF without exception handling:

LEAF 1
Figure 1. LEAF noexcept Error Communication Model

The arrows pointing down indicate the call stack order for the functions f1 through f5: higher level functions calling lower level functions.

Note the call to preload in f3: it caches the passed E-objects of types E1 and E3 in the returned object load, where they stay ready to be communicated in case any function downstream from f3 reports an error. Presumably these objects are relevant to any such failure, but are conveniently accessible only in this scope.

Figure 1 depicts the condition where f5 has detected an error. It calls leaf::new_error to create a new, unique error_id. The passed E-object of type E2 is immediately loaded in the first active context object that provides static storage for it, found in any calling scope (in this case f1), and is associated with the newly-generated error_id (solid arrow);

The error_id itself is returned to the immediate caller f4, usually stored in a result<T> object r. That object takes the path shown by dashed arrows, as each error-neutral function, unable to handle the failure, forwards it to its immediate caller in the returned value — until an error-handling scope is reached.

When the destructor of the load object in f3 executes, it detects that new_error was invoked after its initialization, loads the cached objects of types E1 and E3 in the first active context object that provides static storage for them, found in any calling scope (in this case f1), and associates them with the last generated error_id (solid arrow).

When the error-handling scope f1 is reached, it probes ctx for any E-objects associated with the error_id it received from f2, and processes a list of user-provided error handlers (almost always lambda functions), in order, until it finds a handler with arguments that match the available E-objects. That handler is called to deal with the failure.

Using Exception Handling

The following figure illustrates the slightly different error communication model used when errors are reported by throwing exceptions:

LEAF 2
Figure 2. LEAF Error Communication Model Using Exception Handling

The main difference is that the call to new_error is implicit in the call to the function template leaf::exception, which takes an exception object (in this case of type Ex), and returns an exception object of unspecified type that derives publicly from Ex and from error_id.

In addition to the error_id being transported in the returned exception object, it is possible for error-neutral scopes to catch(error_id const &) if they need to intercept any LEAF-specific exception.

Interoperability

Ideally, when an error is detected, a program using LEAF would always call new_error, ensuring that each encountered error is definitely assigned a unique error_id, which then is reliably delivered, by an exception or by a result<T> object, to the appropriate error-handling scope.

Alas, this is not always possible.

For example, the error may need to be communicated through uncooperative 3rd-party interfaces. To facilitate this transmission, a error ID may be encoded in a std::error_code. As long as a 3rd-party interface understands std::error_code, it should be compatible with LEAF.

Further, it is sometimes necessary to communicate errors through an interface that does not even use std::error_code. An example of this is when an external lower-level library throws an exception, which is unlikely to be able to carry an error_id.

To support this tricky use case, LEAF provides the function current_error, which returns the error ID returned by the most recent call (from this thrad) to new_error. One possible approach is to use the following logic (implemented by augment_id):

  1. Before calling the (possibly uncooperative) API, call current_error and store the returned value.

  2. Call the API, then call current_error again:

    1. If this returns the same value as before, pass the error objects to new_error to associate them with a new error_id;

    2. else, associate the error objects with the error_id value returned by the second call to current_error.

Note that if the above logic is nested (e.g. one function calling another), new_error will be called only by the inner-most function, because that call guarantees that all calling functions will hit the else branch.

To avoid ambiguities, whenever possible, use the exception function template when throwing exceptions to ensure that the exception object transports a unique error_id; better yet, use the LEAF_THROW macro, which in addition will capture __FILE__ and __LINE__.

E-types

With LEAF, users can efficiently associate with errors or with exceptions any number of values that pertain to a failure. These values may be of any no-throw movable type E for which is_e_type<E>::value is true. The expectation is that this template will be specialized as needed for e.g. all user-defined error code enums.

Formally, types E for which is_e_type<E>::value is true are called E-types. Objects of those types are called error objects or E-objects.

The main is_e_type template is defined so that is_e_type<E>::value is true when E is:

  • any type which defines an accessible data member value.

  • any type E for which std::is_base_of<std::exception, E>::value is true,

  • std::exception_ptr,

Often, error values that need to be communicated are of generic types (e.g. std::string). Such values should be enclosed in a C-struct that acts as their compile-time identifier and gives them semantic meaning. Examples:

struct e_input_name  { std::string value; };
struct e_output_name { std::string value; };

struct e_minimum_temperature { float value; };
struct e_maximum_temperature { float value; };

By convention, the enclosing C-struct names use the e_ prefix.


Automatic Deduction of context Types

In LEAF, E-objects are always stored in context<E…​> objects, typically created in the local scope of an error handling function.

While it is possible to instantiate the context class template directly with a list of E-types, this is prone to errors. Consider that attempts to communicate an E-object of a type for which no active context provides storage lead to that object being discarded; therefore, it is critical that any E-type required by a handler in order to deal with a given failure participates in the instantiation of the context template.

The possibility of this mismatch can be eliminated by automatically deducing the E…​ types used to instantiate the context template from the list of handlers that actually recognize and recover from various error conditions. This, in fact, is how try_handle_all, try_handle_some and try_catch work. For example:

leaf::try_handle_all(

  [&]
  {
    // Operations which may fail (1)
  },

  []( my_error_enum x ) (2)
  {
    ...
  },

  []( read_file_error_enum y, e_file_name const & fn ) (3)
  {
    ...
  },

  []
  {
    ...
  });
1 The try_handle_all scope that invoked this lambda contains a local object of automatically deduced type context<my_error_enum, read_file_error_enum, e_file_name>. Reported E-objects of any other type are discarded, because they are not needed in order to recover from errors.
2 Reported E-objects of type my_error_enum will be loaded in the context (rather than discarded), because they are needed by this handler.
3 Reported E-objects of type read_file_error_enum or e_file_name will be loaded in the context (rather than discarded), because they are needed by this handler.

Loading

When an E-object is loaded, it is immediately moved into an active context object, usually local to a try_handle_some, a try_handle_all or a try_catch scope in the calling thread, where it becomes uniquely associated with a specific error_id — or discarded if storage is not available.

Various LEAF functions take a list of E-objects to load. As an example, if a function copy_file that takes the name of the input file and the name of the output file as its arguments detects a failure, it could communicate an error code ec, plus the two relevant file names using new_error:

return leaf::new_error( ec, e_input_name{n1}, e_output_name{n2} );

Alternatively, E-objects may be loaded using a result<T> that is already communicating an error. This way they become associated with that error, rather than with a new error:

leaf::result<int> f();

leaf::result<void> g( char const * fn )
{
  if( leaf::result<int> fr = f() )
  {
    // Use *fr, then...
    return { }; // ...indicate success.
  }
  else
  {
    // f() failed, associate an additional e_file_name with the failure.
    return fr.load( e_file_name{fn} );
  }
}

Accumulation

"Accumulating" an E-object is similar to "loading" it, but where loading takes an E-object, moves it to an active context and associates it with a particular error_id, accumulation takes a function and calls it with the E-object currently stored in the context, associated with the error_id. If no such E-object is available, a new one is default-initialized and then passed to the function.

For example, if an operation that involves many different files fails, a program may provide for collecting all relevant file names in a e_relevant_file_names object:

struct e_relevant_file_names
{
  std::vector<std::string> value;
};

leaf::result<void> operation( char const * file_name )
{
  if( leaf::result<int> r = try_something() )
  {
    ....
    return { }; (1)
  }
  else
  {
    return r.accumulate( (2)
      [&]( e_relevant_file_names & e )
      {
        e.value.push_back(file_name);
      } );
  }
}
1 Indicate success to the caller.
2 try_something failed — add file_name to the e_relevant_file_names object, associated with the error_id communicated in r.

As is always the case with LEAF, the accumulation (or loading) only takes place if a handler passed to try_handle_some, try_handle_all or try_catch takes an argument of type e_relevant_file_names; otherwise the active context would not provide storage for this type and the corresponding accumulation code would not be executed.

In other words, the accumulation of e_relevant_file_names will only occur if an error-handling caller function actually needs that information.


Using preload

It is not typical for an error-initiating function to be able to supply all of the data needed by the error-handling function in order to recover from the failure. For example, a function that reports a FILE operation failure may not have access to the file name, yet an error handling function needs it in order to print a useful error message.

Of course the file name is typically readily available in the call stack leading to the failed FILE operation. In the example below, while parse_info can’t report the file name, parse_file can and does:

leaf::result<info> parse_info( FILE * f ) noexcept; (1)

leaf::result<info> parse_file( char const * file_name ) noexcept
{
  auto load = leaf::preload( leaf::e_file_name{file_name} ); (2)

  if( FILE * f = fopen(file_name,"r") )
  {
    auto r = parse_info(f);
    fclose(f);
    return r;
  }
  else
    return leaf::new_error( error_enum::file_open_error );
}
1 parse_info parses f, communicating errors using result<info>.
2 Using preload ensures that the file name is included with any error reported out of parse_file. All we need to do is hold on to the returned object load: when it expires, if an error is being reported, the passed e_file_name value will be automatically associated with it.

For preload to work, it must succeed in associating the passed E-objects with the correct error_id. The algorithm used to achieve this is as follows:

  • If the calling thread has invoked new_error since the call to preload, the E-objects are associated with the error_id returned by current_error. This association effectively targets the error_id value carried in the most recently created result<T> object or the exception object most recently returned by leaf::exception.

  • Else, if std::uncaught_exception() is true, the E-objects are associated with the error_id returned by new_error. This association targets exception objects that were not created using leaf::exception and therefore do not carry an error_id (see Interoperability).


Capturing errno with defer

Consider the following function:

void read_file(FILE * f) {
  ....
  size_t nr=fread(buf,1,count,f);
  if( ferror(f) )
    throw leaf::exception( file_read_error(), e_errno{errno} );
  ....
}

It is pretty straight-forward, reporting e_errno as it detects a ferror. But what if it calls fread multiple times?

void read_file(FILE * f) {
  ....
  size_t nr1=fread(buf1,1,count1,f);
  if( ferror(f) )
    throw leaf::exception( file_read_error(), e_errno{errno} );

  size_t nr2=fread(buf2,1,count2,f);
  if( ferror(f) )
    throw leaf::exception( file_read_error(), e_errno{errno} );

  size_t nr3=fread(buf3,1,count3,f);
  if( ferror(f) )
    throw leaf::exception( file_read_error(), e_errno{errno} );
  ....
}

Ideally, associating e_errno with each exception should be automated. One way to achieve this is to not call fread directly, but wrap it in another function which checks for ferror and associates the e_errno with the exception it throws.

Using preload we can solve a very similar problem without a wrapper function, but that technique does not work for e_errno because preload would capture errno before a fread call was attempted, at which point errno is probably 0 — or, worse, leftover from a previous I/O failure.

The solution is to use defer, so we don’t have to remember to include e_errno with each exception; errno will be associated automatically with any exception that escapes read_file:

void read_file(FILE * f) {

  auto load = leaf::defer([]{ return e_errno{errno}; });

  ....
  size_t nr1=fread(buf1,1,count1,f);
  if( ferror(f) )
    throw leaf::exception(file_read_error());

  size_t nr2=fread(buf2,1,count2,f);
  if( ferror(f) )
    throw leaf::exception(file_read_error());

  size_t nr3=fread(buf3,1,count3,f);
  if( ferror(f) )
    throw leaf::exception(file_read_error());
  ....
}

This works similarly to preload, except that the capturing of the errno is deferred until the destructor of the load object is called, which calls the passed lambda function to obtain the errno.

This technique works exactly the same way when errors are reported using leaf::result rather than by throwing exceptions.
Keep in mind that the function passed to defer, if invoked, is being executed in the destructor of the load object; make sure it does not throw exceptions.

Deferred accumulate

Let’s say we want to build a record of file locations a given error passes through on its way to be handled. We couldn’t do it with preload, because in this case we need to accumulate information, rather than store it.

One option would be to call the error_id member function accumulate or the result member function accumulate, but these are more convenient when we have a specific error object in our hands, rather than when we just want the information accumulated no matter what the error is.

Usually, the best option is to use accumulate, which works similarly to preload, but it uses the familiar accumulate interface instead:

struct e_trace
{
  struct rec
  {
    char const * file;
    int line;
  };
  std::deque<rec> value;
};

leaf::result<int> f1();
leaf::result<int> f2();

leaf::result<int> sum()
{
  auto acc = leaf::accumulate( []( e_trace & x ) (1)
  {
    x.push_back(e_trace::rec{__FILE__, __LINE__});
  } );

  LEAF_AUTO(a, f1()); (2)
  LEAF_AUTO(b, f2()); (3)
  return a + b; (4)
}
1 This lambda will be called in case an error is communicated by either f1 or f2 (below), but only if the error handling scope needs an e_trace.
2 Call f1, return error or get a value in a.
3 Call f2, return error or get a value in b.
4 Compute result.
Keep in mind that the function passed to accumulate, if invoked, is being executed in the destructor of the acc object; make sure it does not throw exceptions.

Working with Remote Handlers

Consider this snippet:

leaf::try_handle_all(

  [&]
  {
    // Operations which may fail
  },

  []( my_error_enum x )
  {
    ...
  },

  []( read_file_error_enum y, e_file_name const & fn )
  {
    ...
  },

  []
  {
    ...
  });

Looks pretty simple and clean, but what if we need to attempt a different set of operations yet use the same handlers? We could repeat the same thing with a different lambda passed as TryBlock for try_handle_all:

leaf::try_handle_all(

  [&]
  {
    // Different operations which may fail
  },

  []( my_error_enum x )
  {
    ...
  },

  []( read_file_error_enum y, e_file_name const & fn )
  {
    ...
  },

  []
  {
    ...
  });

That works, but LEAF also allows error handlers to be captured and reused. This API is actually very easy to use if a bit unintuitive. This is how a set of handlers can be captured:

auto handle_error = []( leaf::error_info const & error )
{
  return leaf::remote_handle_all( error, (1)

    []( my_error_enum x )
    {
      ...
    },

    []( read_file_error_enum y, e_file_name const & fn )
    {
      ...
    },

    []
    {
      ...
    });
};
1 The helper function remote_handle_all, as well as its alternatives remote_handle_some and remote_handle_exception have no purpose other than to enable capturing of remote handlers; do not call them in any other case.

The tricky bit is to keep in mind that the call to the helper function leaf::remote_handle_all does not occur at this time; all that happens is that its gnarly return type is captured by auto, enabling LEAF to later "know" what kind handlers the handle_error function invokes.

With this in place, reusing these so-called remote handlers is a simple matter of calling remote_try_handle_all instead of try_handle_all:

leaf::remote_try_handle_all(
  [&]
  {
    // Operations which may fail (1)
  },
  [&]( leaf::error_info const & error )
  {
    return handle_error(error); (3)
  } );

leaf::remote_try_handle_all(
  [&]
  {
    // Different operations which may fail (2)
  },
  [&]( leaf::error_info const & error )
  {
    return handle_error(error); (3)
  } );
1 One set of operations which may fail…​
2 A different set of operations which may fail…​
3 …​ both using the same handle_error capture we created earlier.
The captured lambda function must take at least one argument of type leaf::error_info const &, because LEAF invokes the error handling lambda function we pass to remote_try_handle_all with a leaf::error_info. Note however that LEAF does not call handle_error directly, which means that it can take any additional arguments it needs in order to deal with failures, as long as they can be supplied when it is invoked.
LEAF provides three sets of "remote handler" APIs, "handle_all" (as presented above), "handle_some" and "handle_exception", and it is critical that they are not mixed up. Since in this example the handle_error lambda calls the helper function remote_handle_all, it can only be used in a call to remote_try_handle_all. If we needed a capture that can be used with e.g. remote_try_catch, it must be calling the remote_handle_exception helper function instead.

Transporting Error Objects Between Threads

E-objects use automatic storage duration, stored in an instance of the context template in the scope of e.g. try_handle_some, try_handle_all or try_catch functions. When using concurrency, we need a mechanism to collect E-objects in one thread, then use them to handle errors in another thread.

LEAF offers two interfaces for this purpose, one using result<T>, and another designed for programs that use exception handling.

Using result<T>

Let’s assume we have a task that we want to launch asynchronously, which produces a task_result but could also fail:

leaf::result<task_result> task();

Because the task will run asynchronously, in case of a failure we need it to capture the relevant E-objects but not handle errors. To this end, in the main thread we first create a remote handler which we will later use to handle errors from each completed asynchronous task (see Working with Remote Handlers):

auto handle_error = []( leaf::error_info const & error )
{
  return leaf::remote_handle_some( error,

    []( E1 e1, E2 e2 )
    {
      //Deal with E1, E2
      ....
      return { };
    },

    []( E3 e3 )
    {
      //Deal with E3
      ....
      return { };
    } );
};

Why did we start with this step? Because we need to create a context object to collect the E-objects we need. We could just instantiate the context template with E1, E2 and E3, but that would be prone to errors, since it could get out of sync with the handlers we use. Thankfully LEAF can deduce the types we need automatically from the remote handler we created. To create our context object, we just call make_shared_context:

std::shared_ptr<leaf::polymorphic_context> ctx = leaf::make_shared_context(&handle_error);

The polymorphic_context type is an abstract base class that has the same members as any instance of the context class template, allowing us to erase its exact type. So in this case what we’re holding in ctx is a context<E1, E2, E3>, which were deduced automatically from the type of the handle_error object we passed to make_shared_context.

We’re now ready to launch our asynchronous task:

std::future<leaf::result<task_result>> launch_task()
{
  return std::async(
    std::launch::async,
    [&]
    {
      std::shared_ptr<leaf::polymorphic_context> ctx = leaf::make_shared_context(&handle_error);
      return leaf::capture(ctx, &task);
    } );
}

That’s it! Later when we get the std::future, we can process the returned result<task_result> in a call to remote_try_handle_some, using the handle_error remote handler we created earlier, as if it was generated locally:

//std::future<leaf::result<task_result>> fut;
fut.wait();

return leaf::remote_try_handle_some(

  [&]() -> leaf::result<void>
  {
    LEAF_AUTO(r, fut.get());
    //Success!
    return { }
  },

  [&]( leaf::error_info const & error )
  {
    return handle_error(error); // Invoke the remote handler we captured earlier.
  } );

The reason this works is that in case it communicates a failure, leaf::result<T> is able to hold a shared_ptr<polymorphic_context> object. That is why earlier instead of calling task() directly, we called leaf::capture: it calls the passed function, and in case it fails it stores the shared_ptr<polymorphic_context> we created in the returned result<T>, which now doesn’t just communicate the fact that an error has occurred, but also holds the context object that remote_try_handle_some needs in order to find a matching handler.

Follow this link to see a complete example program: capture_in_result.cpp.

Using Exception Handling

Let’s assume we have a task which produces a task_result but could also throw:

task_result task();

Just like we saw in Using result<T>, first we will create a remote handler:

auto handle_error = []( leaf::error_info const & error )
{
  return leaf::remote_handle_exception( error,

    []( E1 e1, E2 e2 )
    {
      //Deal with E1, E2
      ....
      return { };
    },

    []( E3 e3 )
    {
      //Deal with E3
      ....
      return { };
    } );
};
The handler looks almost the same as the one we created in Using result<T>, but note the difference that here we call the helper function remote_handle_exception rather than remote_handle_some. This is important, because we will later use handle_error with remote_try_catch, not with remote_try_handle_some.

Launching the task looks the same as before, except that we don’t use result<T>:

std::future<task_result> launch_task()
{
  return std::async(
    std::launch::async,
    [&]
    {
      std::shared_ptr<leaf::polymorphic_context> ctx = leaf::make_shared_context(&handle_error);
      return leaf::capture(ctx, &task);
    } );
}

That’s it! Later when we get the std::future, we can process the returned task_result in a call to remote_try_catch, using the handle_error remote handler we created earlier, as if it was generated locally:

//std::future<task_result> fut;
fut.wait();

return leaf::remote_try_catch(

  [&]
  {
    task_result r = fut.get(); // Throws on error
    //Success!
  },

  [&]( leaf::error_info const & error )
  {
    return handle_error(error); // Invoke the remote handler we captured earlier.
  } );

This works similarly to using result<T>, except that the std::shared_ptr<polymorphic_context> is transported in an exception object (of unspecified type which remote_try_catch recognizes and then automatically unwraps the original exception).

Follow this link to see a complete example program: capture_in_exception.cpp.

Working with Disparate Error Types

Because most libraries define their own mechanism for reporting errors, programmers often need to use multiple incompatible error-initiating interfaces in the same program. This led to the introduction of boost::system::error_code which later became std::error_code. Each std::error_code object is assigned an error_category. Libraries that communicate errors in terms of std::error_code define their own error_category. For libraries that do not, the user can "easily" define a custom error_category and still translate domain-specific error codes to std::error_code.

But let’s take a step back and consider why did we want to express every error in terms of the same static type, std::error_code in the first place? We need this translation because the C++ static type-checking system makes it difficult to write functions that may return error objects of the disparate static types used by different libraries. Outside of this limitation, it would be preferable to be able to write functions that can communicate errors in terms of arbitrary C++ types, as needed.

To drive this point further, consider the real world problem of mixing boost::system::error_code and std::error_code in the same program. In theory, both systems are designed to be able to express one error code in terms of the other. In practice, describing a generic system for error categorization in terms of another generic system for error categorization may not be trivial.

Ideally, functions should be able to communicate different error types without having to translate between them. Using LEAF, a scope that is able to handle either std::error_code or boost::system::error_code would look like this:

return try_handle_some(

  []() -> leaf::result<T> (1)
  {
    // Call operations which may report std::error_code and boost::system::error_code.
  },

  []( std::error_code const & e )
  {
    .... (2)
  },

  []( boost::system::error_code const & e )
  {
    .... (3)
  } );
1 Communicate errors via result<T>.
2 Handle std::error_code errors.
3 Handle boost::system::error_code errors.

And here is a function which, using LEAF, forwards either std::error_code or boost::system::error_code objects reported by lower level functions:

leaf::result<void> f()
{
  if( std::error_code ec = g1() )
    return leaf::new_error(ec);

  if( boost::system::error_code ec = g2() )
    return leaf::new_error(ec);

  return {};
}

Converting Exceptions to result<T>

It is sometimes necessary to catch exceptions thrown by a lower-level library function, and report the error through different means, to a higher-level library which may not use exception handling.

Suppose we have an exception type hierarchy and a function compute_answer_throws:

class error_base: public virtual std::exception { };
class error_a: public virtual error_base { };
class error_b: public virtual error_base { };
class error_c: public virtual error_base { };

int compute_answer_throws()
{
  switch( rand()%4 )
  {
    default: return 42;
    case 1: throw error_a();
    case 2: throw error_b();
    case 3: throw error_c();
  }
}

We can write a simple wrapper using exception_to_result, which calls compute_answer_throws and switches to result<int> for error handling:

leaf::result<int> compute_answer() noexcept
{
  return leaf::exception_to_result<error_a, error_b>(
    []
    {
      return compute_answer_throws();
    } );
}

(As a demonstration, compute_answer specifically converts exceptions of type error_a or error_b, while it leaves error_c to be captured by std::exception_ptr).

Here is a simple function which prints successfully computed answers, forwarding any error (originally reported by throwing an exception) to its caller:

leaf::result<void> print_answer() noexcept
{
  LEAF_AUTO(answer, compute_answer());
  std::cout << "Answer: " << answer << std::endl;
  return { };
}

Finally, here is a scope that handles the errors (which used to be exception objects):

leaf::try_handle_all(

  []() -> leaf::result<void>
  {
    LEAF_CHECK(print_answer());
    return { };
  },

  []( error_a const & e )
  {
    std::cerr << "Error A!" << std::endl;
  },

  []( error_b const & e )
  {
    std::cerr << "Error B!" << std::endl;
  },

  []
  {
    std::cerr << "Unknown error!" << std::endl;
  } );
The complete program illustrating this technique is available here.

Using augment_id in (Lua) C-callbacks

Communicating information pertaining to a failure detected in a C callback is tricky, because C callbacks are limited to a specific static signature, which may not use C++ types.

LEAF makes this easy. As an example, we’ll write a program that uses Lua and reports a failure from a C++ function registered as a C callback, called from a Lua program. The failure will be propagated from C++, through the Lua interpreter (written in C), back to the C++ function which called it.

C/C++ functions designed to be invoked from a Lua program must use the following signature:

int do_work( lua_State * L ) ;

Arguments are passed on the Lua stack (which is accessible through L). Results too are pushed onto the Lua stack.

First, let’s initialize the Lua interpreter and register do_work as a C callback, available for Lua programs to call:

std::shared_ptr<lua_State> init_lua_state() noexcept
{
  std::shared_ptr<lua_State> L(lua_open(),&lua_close); (1)

  lua_register( &*L, "do_work", &do_work ); (2)

  luaL_dostring( &*L, "\ (3)
\n      function call_do_work()\
\n          return do_work()\
\n      end" );

  return L;
}
1 Create a new lua_State. We’ll use std::shared_ptr for automatic cleanup.
2 Register the do_work C++ function as a C callback, under the global name "do_work". With this, calls from Lua programs to do_work will land in the do_work C++ function.
3 Pass some Lua code as a C string literal to Lua. This creates a global Lua function called call_do_work, which we will later ask Lua to execute.

Next, let’s define our enum used to communicate do_work failures:

enum do_work_error_code
{
  ec1=1,
  ec2
};

namespace boost { namespace leaf {

  template<> struct is_e_type<do_work_error_code>: std::true_type { };

} }

We’re now ready to define the do_work callback function:

int do_work( lua_State * L ) noexcept
{
  bool success=rand()%2; (1)
  if( success )
  {
    lua_pushnumber(L,42); (2)
    return 1;
  }
  else
  {
    leaf::new_error(ec1); (3)
    return luaL_error(L,"do_work_error"); (4)
  }
}
1 "Sometimes" do_work fails.
2 In case of success, push the result on the Lua stack, return back to Lua.
3 Generate a new error_id and associate a do_work_error_code with it. Normally, we’d return this in a leaf::result<T>, but the do_work function signature (required by Lua) does not permit this.
4 Tell the Lua interpreter to abort the Lua program.

Now we’ll write the function that calls the Lua interpreter to execute the Lua function call_do_work, which in turn calls do_work. We’ll return result<int>, so that our caller can get the answer in case of success, or an error:

leaf::result<int> call_lua( lua_State * L )
{
  lua_getfield( L, LUA_GLOBALSINDEX, "call_do_work" );
  augment_id augment;
  if( int err=lua_pcall(L,0,1,0) ) (1)
  {
    auto load = leaf::preload( e_lua_error_message{lua_tostring(L,1)} ); (2)
    lua_pop(L,1);
    return aughent.get_error( e_lua_pcall_error{err} ); (3)
  }
  else
  {
    int answer=lua_tonumber(L,-1); (4)
    lua_pop(L,1);
    return answer;
  }
}
1 Ask the Lua interpreter to call the global Lua function call_do_work.
2 preload works as usual.
3 get_error will return the error_id generated in our Lua callback. This is the same error_id the preload uses as well.
4 Success! Just return the int answer.

Finally, here is the main function which exercises call_lua, each time handling any failure:

int main() noexcept
{
  std::shared_ptr<lua_State> L=init_lua_state();

  for( int i=0; i!=10; ++i )
  {
    leaf::try_handle_all(

      [&]() -> leaf::result<void>
      {
        LEAF_AUTO(answer, call_lua(&*L));
        std::cout << "do_work succeeded, answer=" << answer << '\n'; (1)
        return { };
      },

      []( do_work_error_code e ) (2)
      {
        std::cout << "Got do_work_error_code = " << e <<  "!\n";
      },

      []( e_lua_pcall_error const & err, e_lua_error_message const & msg ) (3)
      {
        std::cout << "Got e_lua_pcall_error, Lua error code = " << err.value << ", " << msg.value << "\n";
      },

      []( leaf::error_info const & unmatched )
      {
        std::cerr <<
          "Unknown failure detected" << std::endl <<
          "Cryptic diagnostic information follows" << std::endl <<
          unmatched;
      } );
  }
1 If the call to call_lua succeeded, just print the answer.
2 Handle do_work failures.
3 Handle all other lua_pcall failures.

Follow this link to see the complete program: lua_callback_result.cpp.

Remarkably, the Lua interpreter is C++ exception-safe, even though it is written in C. Here is the same program, this time using a C++ exception to report failures from do_work: lua_callback_eh.cpp.


Diagnostic Information

LEAF is able to automatically generate diagnostic messages that include information about all E-objects available to error handlers. For this purpose, it needs to be able to print objects of user-defined E-types.

To do this, LEAF attempts to bind an unqualified call to operator<<, passing a std::ostream and the E-object. If that fails, it will also attempt to bind operator<< that takes the .value of the E-object. If that also doesn’t compile, the E-object value will not appear in diagnostic messages, though LEAF will still print its type.

Even with E-types that define a printable .value, the user may still want to overload operator<< for the enclosing struct, e.g.:

struct e_errno
{
  int value;

  friend std::ostream & operator<<( std::ostream & os, e_errno const & e )
  {
    return os << "errno = " << e.value << ", \"" << strerror(e.value) << '"';
  }
};

The e_errno type above is designed to hold errno values. The defined operator<< overload will automatically include the output from strerror when e_errno values are printed (LEAF defines e_errno in <boost/leaf/common.hpp>, together with other commonly-used error types).

These automatically-generated diagnostic messages are developer-friendly, but not user-friendly. Therefore, operator<< overloads for E-types should only print technical information in English, and should not attempt to localize strings or to format a user-friendly message; this should be done in error-handling functions specifically designed for that purpose.

Examples

Synopsis

This section lists each public header file in LEAF, documenting the definitions it provides.

LEAF headers are organized as to minimize coupling:

  • Headers needed to report but not handle errors are lighter than headers providing error handling functionality.

  • Headers that provide exception handling or throwing functionality are separate from headers that provide error-handling or reporting but do not use exceptions.

There is also a reference section split in four parts, the contents of each part organized alphabetically:


Error Reporting

LEAF supports reporting errors via a result<T> type or by throwing exceptions. Functions that throw exceptions or use exception handling are defined in separate headers, so that client code that does not use exceptions is not coupled with them.

error.hpp

The header <boost/leaf/error.hpp> contains definitions needed by translation units that report errors but do not throw exceptions.

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  template <class T>
  struct is_e_type
  {
    static constexpr bool value = <<unspecified>>;
  };

  //////////////////////////////////////////

  class error_id
  {
  public:

    error_id() noexcept;

    error_id( std::error_code const & ec ) noexcept;

    int value() const noexcept;
    explicit operator bool() const noexcept;

    std::error_code to_error_code() const noexept;

    friend bool operator==( error_id a, error_id b ) noexcept;
    friend bool operator!=( error_id a, error_id b ) noexcept;
    friend bool operator<( error_id a, error_id b ) noexcept;

    template <class... E>
    error_id load( E && ... e ) const noexcept;

    template <class... F>
    error_id accumulate( F && ... f ) const noexcept;

    friend std::ostream & operator<<( std::ostream & os, error_id x );
  };

  bool is_error_id( std::error_code const & ec ) noexcept;

  template <class... E>
  error_id new_error( E && ... e ) noexcept;

  error_id current_error() noexcept;

  //////////////////////////////////////////

  class polymorphic_context
  {
  protected:

    polymorphic_context() noexcept = default;
    ~polymorphic_context() noexcept = default;

  public:

    virtual void activate() noexcept = 0;
    virtual void deactivate() noexcept = 0;
    virtual bool is_active() const noexcept = 0;

    virtual void propagate() noexcept = 0;

    virtual void print( std::ostream & ) const = 0;
  };

  //////////////////////////////////////////

  template <class Ctx>
  class context_activator
  {
    context_activator( context_activator const & ) = delete;
    context_activator & operator=( context_activator const & ) = delete;

  public:

    explicit context_activator( Ctx & ctx ) noexcept;
    context_activator( context_activator && ) noexcept;
    ~context_activator() noexcept;
  };

} }

template <class Ctx>
context_activator<Ctx> activate_context( Ctx & ctx ) noexcept;

#define LEAF_NEW_ERROR(...) ....
#define LEAF_AUTO(v,r) ....
#define LEAF_CHECK(r) ....

common.hpp

This header contains definitions of commonly-used E-types.

#include <boost/leaf/common.hpp>
namespace boost { namespace leaf {

  struct e_api_function    { .... };
  struct e_file_name       { .... };
  struct e_errno           { .... };
  struct e_at_line         { .... };
  struct e_type_info_name  { .... };
  struct e_source_location { .... };

  namespace windows
  {
    struct e_LastError  { .... };
  }

} }

result.hpp

This header defines a lightweight result<T> template. Note that LEAF error-handling functions can work any external type for which the is_result_type template is specialized, that has value-or-error variant semantics similar to leaf::result<T>.

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  class result
  {
  public:

    result() noexcept;
    result( T && v ) noexcept;
    result( T const & v );

    result( error_id err ) noexcept;
    result( std::error_code const & ec ) noexcept;
    result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;

    result( result && r ) noexcept;

    template <class U>
    result( result<U> && r ) noexcept;

    result & operator=( result && r ) noexcept;

    template <class U>
    result & operator=( result<U> && r ) noexcept;

    explicit operator bool() const noexcept;

    T const & value() const;
    T & value();

    T const & operator*() const;
    T & operator*();

    T const * operator->() const;
    T * operator->();

    <<unspecified-type>> error() noexcept;

    template <class... E>
    error_id load( E && ... e ) noexcept;

    template <class... F>
    error_id accumulate( F && ... f );
  };

  struct bad_result: std::exception { };

} }

preload.hpp

This header defines functions for automatic inclusion of E-objects with any error exiting the scope in which they are invoked. See Using preload, Capturing errno with defer, Deferred accumulate.

The augment_id type is used internally by preload, defer and accumulate to determine the correct error_id to associate error objects with.

#include <boost/leaf/preload.hpp>
namespace boost { namespace leaf {

  template <class... E>
  <<unspecified-type>> preload( E && ... e ) noexcept;

  template <class... F>
  <<unspecified-type>> defer( F && ... f ) noexcept;

  template <class... F>
  <<unspecified-type>> accumulate( F && ... f ) noexcept;

  class augment_id
  {
  public:

    augment_id() noexcept;

    error_id check_error() const noexcept;

    template <class... E>
    error_id get_error( E && ... e ) const noexcept;
  };

} }

exception.hpp

This header provides support for throwing exceptions.

#include <boost/leaf/exception.hpp>
#include <boost/leaf/error.hpp>

namespace boost { namespace leaf {

  template <class Ex, class... E>
  <<unspecified>> exception( Ex && ex, E && ... e ) noexcept;

} }

#define LEAF_EXCEPTION(...) ....

#define LEAF_THROW(...) ....

capture.hpp

This header is used when transporting E-objects between threads, or to convert exceptions to result<T>.

#include <boost/leaf/capture_exception.hpp>
namespace boost { namespace leaf {

  template <class F, class... A>
  decltype(std::declval<F>()(std::forward<A>(std::declval<A>())...))
  capture(std::shared_ptr<polymorphic_context> && ctx, F && f, A... a);

  template <class... Ex, class F>
  <<result<T>-deduced>> exception_to_result( F && f ) noexcept;

} }

Error Handling

Error-handling headers are designed to minimize coupling:

  • Translation units that work with context objects but do not handle errors should #include <boost/leaf/context.hpp>;

  • Translation units that handle errors but do not catch exceptions should #include <boost/leaf/handle_error.hpp>;

  • Translation units that do catch exceptions should #include <boost/leaf/handle_exception.hpp>.

Namespace-scope error-handling functions contain the word try_ in their name and use the following conventions:

  • Functions that do not use the remote_ prefix take a list of error handlers; functions that do, take a single error-handling function, which internally captures the list of error handlers. See Working with Remote Handlers.

  • Functions that are designed to work with a result<T> type (see is_result_type) use the _all or _some suffix; the former require (at compile time) the user-supplied set of handlers to definitely handle any reported error, while the latter allow for handlers to recognize and handle some errors, forwarding others to the caller.

  • An _all or a _some function does not catch or handle exceptions unless at least one of the user-supplied handlers uses the catch_ template. All other error-handling functions catch or can handle exceptions.

This is summarized in the table below:

Table 1. Namespace-Scope Error-Handling Functions

Handles result<T> Errors

Handles Exceptions

[remote_]try_handle_all

Yes

*

[remote_]try_handle_some

Yes

*

[remote_]try_catch

No

Yes

* Handles exceptions iff at least one of the supplied handlers uses catch_
(Dispatched statically; please #include <boost/leaf/handle_exception.hpp>)

The above error-handling functions:

  1. Create an internal context<E…​> object ctx, deducing the E…​ types automatically from the arguments of the supplied handlers;

  2. Attempt the set of operations contained in the passed TryBlock function;

  3. If that fails, they invoke an appropriate error handler to handle the error.

In addition, the context template provides lower-level error handling member functions, handle_error and remote_handle_error, which select an error handler based on available error objects in *this, associated with a supplied error_id. These functions are designed to be called after the caller has detected a failure; they do not use a result type and can not deal with exceptions. Use one of the try_ functions (above) for these cases.


context.hpp

This header defines the context template, which is used in error-handling scopes to provide storage for the error objects needed by user-defined error-handling functions, and to handle errors.

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  class context
  {
    context( context const & ) = delete;
    context & operator=( context const & ) = delete;

  public:

    context() noexcept;
    context( context && x ) noexcept;
    ~context() noexcept;

    void activate() noexcept;
    void deactivate() noexcept;
    bool is_active() const noexcept;

    void propagate () noexcept;

    void print( std::ostream & os ) const;

    template <class R, class... H>
    R handle_error( R &, H && ... ) const;

    template <class R, class RemoteH>
    R remote_handle_error( R &, RemoteH && ) const;
  };

  //////////////////////////////////////////

  template <class RemoteH>
  using context_type_from_remote_handler = typename <<unspecified>>::type;

  template <class RemoteH>
  context_type_from_remote_handler<RemoteH> make_context( RemoteH const * = 0 );

  template <class RemoteH>
  std::shared_ptr<polymorphic_context> make_shared_context( RemoteH const * = 0 );

  template <class RemoteH, class Alloc>
  std::shared_ptr<polymorphic_context> allocate_shared_context( Alloc alloc, RemoteH const * = 0 );

} }

handle_error.hpp

This header defines functions and types that can be used to handle errors but not catch exceptions.

#include <boost/leaf/handle_error.hpp>
#include <boost/leaf/context.hpp>

namespace boost { namespace leaf {

  template <class TryBlock, class... H>
  typename std::decay<decltype(std::declval<TryBlock>()().value())>::type
  try_handle_all( TryBlock && try_block, H && ... h );

  template <class TryBlock, class... H>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  try_handle_some( TryBlock && try_block, H && ... h );

  template <class TryBlock, class RemoteH>
  typename std::decay<decltype(std::declval<TryBlock>()().value())>::type
  remote_try_handle_all( TryBlock && try_block, RemoteH && h );

  template <class TryBlock, class RemoteH>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  remote_try_handle_some( TryBlock && try_block, RemoteH && h );

  //////////////////////////////////////////

  template <class Enum>
  class match;

  template <class Enum, class ErrorConditionEnum = Enum>
  struct condition;

  //////////////////////////////////////////

  class error_info
  {
    //Constructors unspecified

  public:

    error_id error() const noexcept;

    bool exception_caught() const noexcept;
    std::exception const * exception() const noexcept;

    friend std::ostream & operator<<( std::ostream & os, error_info const & x );
  };

  class diagnostic_info: public error_info
  {
    //Constructors unspecified

    friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x );
  };

  class verbose_diagnostic_info: public error_info
  {
    //Constructors unspecified

    friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x );
  };

} }

handle_exception.hpp

This header:

  • Defines namespace-scope functions and types that can be used to catch exceptions.

  • Enables all functions using the _some or _all suffix (defined in handle_error.hpp) to handle exceptions, not only failures communicated by result<T>.

#include <boost/leaf/handle_exception.hpp>
#include <boost/leaf/handle_error.hpp>

namespace boost { namespace leaf {

  template <class TryBlock, class... H>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  try_catch( TryBlock && try_block, H && ... h );

  template <class TryBlock, class RemoteH>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  remote_try_catch( TryBlock && try_block, RemoteH && h );

  //////////////////////////////////////////

  template <class... Ex>
  struct catch_;

} }

Reference: Traits

is_e_type

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  template <class E>
  struct is_e_type
  {
    static constexpr bool value = <<exact_definition_unspecified>>;
  };

} }

Users specialize the is_e_type template to register error types with LEAF; see E-types.

The default is_e_type template defines value as true for:

  • Any type which defines an accessible data member value;

  • Any type E for which std::is_base_of<std::exception, E>::value is true (see exception_to_result);

  • std::exception_ptr.


is_result_type

#include <boost/leaf/error.hpp>>
namespace boost { namespace leaf {

  template <class R>
  struct is_result_type: std::false_type
  {
  };

} }

The error-handling functionality provided by try_handle_some, try_handle_all and try_catch — including the ability to load error objects of arbitrary types — is compatible with any external “result<T>” type R, as long as for a given object r of type R:

  • If bool(r) is true, r indicates success, in which case it is valid to call r.value() to recover the “T” value.

  • Otherwise r indicates a failure, in which case it is valid to call r.error(). The returned value is used to initialize an error_id (note: error_id can be initialized by std::error_code).

To use an external “result<T>” type R, you must specialize the is_result_type template so that is_result_type<R>::value evaluates to true.

Naturally, the provided leaf::result<T> class template satisfies these requirements. In addition, it allows error objects to be transported across thread boundaries, using a std::shared_ptr<polymorphic_context>.

Reference: Functions

The contents of each Reference section are organized alphabetically.

accumulate

#include <boost/leaf/preload.hpp>
namespace boost { namespace leaf {

  template <class... F>
  <<unspecified-type>> accumulate( F && ... f ) noexcept;

} }
Requirements:

Each of fi in f…​ must be a function that does not throw exceptions and takes a single argument of type Ei such that:

  • Ei defines an accessible no-throw default constructor, and

  • is_e_type<Ei>::value is true.

Effects:

All f…​ objects are forwarded and stored into the returned object of unspecified type, which should be captured by auto and kept alive in the calling scope. When that object is destroyed:

  • If new_error was invoked (by the calling thread) since the object returned by accumulate was created, each of the stored f…​ is called with the corresponding E-object currently uniquely associated with current_error, or with a new default-initialized instance of that E-type if no such E-object currently exists;

  • Otherwise, if std::unhandled_exception() returns true, each of the stored f…​ is called with the corresponding E-object currently uniquely associated with the value returned by new_error, or with a new default-initialized instance of that E-type if no such E-object currently exists.

The stored f…​ objects are discarded.

It is critical that the passed functions do not throw exceptions: they are called from within a destructor.
Be extra careful, since Accumulation naturally may need to allocate memory. In this case consider using error_id::accumulate or result::accumulate instead, invoked not from a destructor, in which case throwing exceptions would be okay.
See also Deferred accumulate from the Tutorial.

activate_context

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  template <class Ctx>
  context_activator<Ctx> activate_context( Ctx & ctx ) noexcept
  {
    return context_activator<Ctx>(ctx);
  }

} }

allocate_shared_context

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class RemoteH, class Alloc>
  std::shared_ptr<polymorphic_context> allocate_shared_context( Alloc alloc, RemoteH const * = 0 )
  {
    return std::allocate_shared<context_type_from_remote_handler<RemoteH>>(alloc);
  }

} }

capture

#include <boost/leaf/capture_result.hpp>
namespace boost { namespace leaf {

  template <class F, class... A>
  decltype(std::declval<F>()(std::forward<A>(std::declval<A>())...))
  capture(std::shared_ptr<polymorphic_context> && ctx, F && f, A... a);

} }

This function can be used to capture E-objects stored in a context in one thread and transport them to a different thread for handling, either in a result<T> object or in an exception.

Returns:

The same type returned by F.

Effects:

Uses an internal context_activator to activate *ctx, then invokes std::forward<F>(f)(std::forward<A>(a)…​). Then:

  • If the returned value r is not a result<T> type (see is_result_type), it is forwarded to the caller.

  • Otherwise:

    • If !r, the return value of capture is initialized with ctx;

      An object of type leaf::result<T> can be initialized with a std::shared_ptr<leaf::polymorphic_context>.
    • otherwise, it is initialized with r.

In case f throws, capture catches the exception in a std::exception_ptr, and throws a different exception of unspecified type that transports both the std::exception_ptr as well as ctx. This exception type is recognized by try_catch, which automatically unpacks the original exception and propagates the contents of *ctx (presumably, in a different thread).

See also Transporting Error Objects Between Threads from the Tutorial.

context_type_from_remote_handler

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class RemoteH>
  using context_type_from_remote_handler = typename <<unspecified>>::type;

} }
Example Usage:
auto handle_error = []( leaf::error_info const & error )
{
  return leaf::handle_all( error,
    []( e_this const & a, e_that const & b )
    {
      ....
    },
    []( leaf::diagnostic_info const & info )
    {
      ....
    },
    .... );
};

leaf::context_type_from_remote_handler<decltype(handle_error)> ctx;

In the example above, ctx will be of type context<e_this, e_that, leaf::diagnostic_info>, deduced automatically from the handler list in handle_error. This guarantees that ctx provides storage for all E-types that are required by handle_error in order to handle errors.

Alternatively, a suitable context may be created by calling make_context, or allocated dynamically by calling make_shared_context or allocate_shared_context.

current_error

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  error_id current_error() noexcept;

} }
Returns:

The error_id value returned the last time new_error was invoked from the calling thread.

See also preload / defer / accumulate.

defer

#include <boost/leaf/preload.hpp>
namespace boost { namespace leaf {

  template <class... F>
  <<unspecified-type>> defer( F && ... f ) noexcept;

} }
Requirements:

Each of fi in f…​ must be a function that does not throw exceptions, takes no arguments and returns an object of a no-throw movable type Ei for which is_e_type<Ei>::value is true.

Effects:

All f…​ objects are forwarded and stored into the returned object of unspecified type, which should be captured by auto and kept alive in the calling scope. When that object is destroyed:

  • If new_error was invoked (by the calling thread) since the object returned by defer was created, each of the stored f…​ is called, and each returned object is loaded and uniquely associated with current_error;

  • Otherwise, if std::unhandled_exception() returns true, each of the stored f…​ is called, and each returned object is loaded and uniquely associated with the value returned by new_error.

The stored f…​ objects are discarded.

It is critical that the passed functions do not throw exceptions: they are called from within a destructor.
See also Capturing errno with defer from the tutorial.

exception

#include <boost/leaf/exception.hpp>
namespace boost { namespace leaf {

  template <class Ex, class... E>
  <<unspecified>> exception( Ex && ex, E && ... e ) noexcept;

} }
Requirements:
  • Ex must derive from std::exception.

  • For each Ei in E…​, is_e_type<Ei>::value is true.

Returns:

An object of unspecified type which derives publicly from Ex and from class error_id such that:

  • its Ex subobject is initialized by std::forward<Ex>(ex);

  • its error_id subobject is initialized by new_error(std::forward<E>(e)…​).

If thrown, the returned object can be caught as Ex & or as leaf::error_id &.
To automatically capture __FILE__, __LINE__ and __FUNCTION__ with the returned object, use LEAF_EXCEPTION instead of leaf::exception.

exception_to_result

#include <boost/leaf/capture.hpp>
namespace boost { namespace leaf {

  template <class... Ex, class F>
  <<result<T>-deduced>> exception_to_result( F && f ) noexcept;

} }

This function can be used to catch exceptions from a lower-level library and convert them to result<T>.

Returns:

If f returns T, exception_to_result returns result<T>.

Effects:
  1. Catches all exceptions, then captures std::current_exception in a std::exception_ptr object, which is loaded with the returned result<T>.

  2. Attempts to convert the caught exception, using dynamic_cast, to each type Exi in Ex…​. If the cast to Exi succeeds, the Exi slice of the caught exception is loaded with the returned result<T>.

Handlers passed to try_handle_some / try_handle_all should take the converted-to-result exception objects by const & (whereas, in case exceptions are handled directly by try_catch handlers, catch_ should be used instead).

Example:

int compute_answer_throws();

//Call compute_answer, convert exceptions to result<int>
leaf::result<int> compute_answer()
{
  return leaf::exception_to_result<ex_type1, ex_type2>(compute_answer_throws());
}

Later, what used to be the exception types ex_type1 and ex_type2 can be handled by try_handle_some / try_handle_all:

return leaf::try_handle_some(

  [] -> leaf::result<void>
  {
    LEAF_AUTO(answer, compute_answer());
    //Use answer
    ....
    return { };
  },

  []( ex_type1 const & ex1 )
  {
    //Handle ex_type1
    ....
    return { };
  },

  []( ex_type2 const & ex2 )
  {
    //Handle ex_type2
    ....
    return { };
  },

  []( std::exception_ptr const & p )
  {
    //Handle any other exception from compute_answer.
    ....
    return { };
  } );
See also Converting Exceptions to result<T> from the tutorial.

make_context

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class RemoteH>
  context_type_from_remote_handler<RemoteH> make_context( RemoteH const * = 0 )
  {
    return { };
  }

} }

make_shared_context

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class RemoteH>
  std::shared_ptr<polymorphic_context> make_shared_context( RemoteH const * = 0 )
  {
    return std::make_shared<context_type_from_remote_handler<RemoteH>>();
  }

} }
See also Transporting Error Objects Between Threads from the tutorial.

new_error

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  template <class... E>
  error_id new_error( E && ... e ) noexcept;

} }
Requirements:

is_e_type<E>::value must be true for each E.

Effects:

Each of the e…​ objects is loaded and uniquely associated with the returned value.

Returns:

A new error_id value, which is unique across the entire program.

Ensures:

id.value()!=0, where id is the returned error_id.


preload

#include <boost/leaf/preload.hpp>
namespace boost { namespace leaf {

  template <class... E>
  <<unspecified-type>> preload( E && ... e ) noexcept;

} }
Requirements:

is_e_type<E>::value must be true for each E.

Effects:

All e…​ objects are forwarded and stored into the returned object of unspecified type, which should be captured by auto and kept alive in the calling scope. When that object is destroyed:

  • If new_error was invoked (by the calling thread) since the object returned by preload was created, the stored e…​ objects are loaded and become uniquely associated with current_error;

  • Otherwise, if std::unhandled_exception() returns true, the stored e…​ objects are loaded and become uniquely associated with the value returned by new_error;

  • Otherwise, the stored e…​ objects are discarded.

See Using preload from the Tutorial.

remote_try_catch

#include <boost/leaf/handle_exception.hpp>
namespace boost { namespace leaf {

  template <class TryBlock, class RemoteH>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  remote_try_catch( TryBlock && try_block, RemoteH && h );

} }

This function works similarly to remote_try_handle_some, but handles exceptions rather than a result<T> result. Here is an example of how remote handlers should be captured so the captured function is compatible with remote_try_catch:

auto remote_handlers = []( leaf::error_info const & error )
{
  return leaf::remote_handle_exception( error,

    []( my_error_code ec, leaf::e_file_name const & fn )
    {
      ....
    },

    []( my_error_code ec )
    {
      ....
    } );
};

To use the captured remote_handlers, we call remote_try_catch rather than try_catch (the latter requires the handlers to be passed inline):

return leaf::remote_try_catch(
  []
  {
    // Code which may throw
  },

  [&]( leaf::error_info const & error )
  {
    return remote_handlers(error);
  } );
See also Working with Remote Handlers from the Tutorial.

remote_try_handle_all

#include <boost/leaf/handle_error.hpp>
namespace boost { namespace leaf {

  template <class TryBlock, class RemoteH>
  typename std::decay<decltype(std::declval<TryBlock>()().value())>::type
  remote_try_handle_all( TryBlock && try_block, RemoteH && h );

} }

This function works similarly to remote_try_handle_some, but like other “_all” functions, it is required to handle any error (enforced at compile-time). Therefore, the captured remote_handlers must include a handler that matches any error:

auto remote_handlers = []( leaf::error_info const & error )
{
  return leaf::remote_handle_all( error,

    []( my_error_code ec, leaf::e_file_name const & fn )
    {
      ....
    },

    []( my_error_code ec )
    {
      ....
    },

    [] //Matches any error
    {
      ....
    } );
};
For the capture (above) to be compatible with remote_try_handle_all, it must use the helper function remote_handle_all.
See also Working with Remote Handlers from the Tutorial.

remote_try_handle_some

#include <boost/leaf/handle_error.hpp>
namespace boost { namespace leaf {

  template <class TryBlock, class RemoteH>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  remote_try_handle_some( TryBlock && try_block, RemoteH && h );

} }

This function works the same way as try_handle_some and has the same requirements, but rather than taking the handlers inline in a parameter pack, it takes a single function that captures the handlers, created like this:

auto remote_handlers = []( leaf::error_info const & error )
{
  return leaf::remote_handle_some( error,

    []( my_error_code ec, leaf::e_file_name const & fn )
    {
      ....
    },

    []( my_error_code ec )
    {
      ....
    } );
};

Above, the remote_handlers function object captures the two handlers passed to the helper function remote_handle_some. Note that the function itself or the handlers are not called at this point; the only effect is that we now have a function, which we can later invoke to handle errors, using remote_try_handle_some:

return leaf::remote_try_handle_some(
  []
  {
    // Code which may fail
  },

  [&]( leaf::error_info const & error )
  {
    return remote_handlers(error);
  } );

Like try_handle_some, the first thing remote_try_handle_some does is call the passed try_block. If it succeeds, the returned result<T> is forwarded to the caller. Otherwise, it calls h with the leaf::error_info object that represents the error being handled, where we call the remote_handlers function we captured earlier, which will attempt to find a matching handler, as usual.

remote_try_handle_some catches and handles exceptions iff at least one of the supplied remote handlers takes an argument of type that is an instance of the catch_ template; otherwise it is exception-neutral.

Note that it is possible for remote_handlers to take additional arguments that it needs in order to handle errors:

auto remote_handlers = []( leaf::error_info const & error, int a )
{
  return leaf::remote_handle_some( error,

    [&]( my_error_code ec, leaf::e_file_name const & fn )
    {
      use(a);
      ....
    },

    []( my_error_code ec )
    {
      ....
    } );
};

Of course, later it is our responsibility to pass the extra arguments:

return leaf::remote_try_handle_some(
  []
  {
    // Code which may fail
  },
  [&]( leaf::error_info const & error )
  {
    return remote_handlers(error, 42); // Pass 42 for a
  } );
See also Working with Remote Handlers from the Tutorial.

try_catch

#include <boost/leaf/handle_exception.hpp>
namespace boost { namespace leaf {

  template <class TryBlock, class... H>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  try_catch( TryBlock && try_block, H && ... h );

} }

The try_catch function works similarly to try_handle_some, except that it does not use or understand the semantics of result<T> types; instead:

  • It assumes that the try_block throws to indicate a failure, in which case try_catch will attempt to find a matching handler among h…​;

  • If a suitable handler isn’t found, the original exception is re-thrown using throw;.

See also Five Minute Introduction Using Exception Handling.

try_handle_all

#include <boost/leaf/handle_error.hpp>
namespace boost { namespace leaf {

  template <class TryBlock, class... H>
  typename std::decay<decltype(std::declval<TryBlock>()().value())>::type
  try_handle_all( TryBlock && try_block, H && ... h );

} }

The try_handle_all function works similarly to try_handle_some, except:

  • In addition, it requires the passed handler pack to be able to handle any error, which is enforced at compile time, and

  • because it is required to handle all errors, try_handle_all unpacks the result<T> object r returned by the try_block, returning r.value() instead of r.

See also Five Minute Introduction Using result<T>.

try_handle_some

#include <boost/leaf/handle_error.hpp>
namespace boost { namespace leaf {

  template <class TryBlock, class... H>
  typename std::decay<decltype(std::declval<TryBlock>()())>::type
  try_handle_some( TryBlock && try_block, H && ... h );

} }
Requirements:
  • The try_block function may not take any arguments.

  • The type R returned by the try_block function must be a result<T> type (see is_result_type). It is valid for the try_block to return leaf::result<T>, however this is not a requirement.

  • Each of the h…​ functions:

    • may take arguments of E-types, either by value or by const &, or as a const *;

    • may take arguments, either by value or by const &, of the predicate type match<E, V…​>, where E is an E-type or an instance of the condition class template.

    • may take arguments, either by value or by const &, of the predicate type catch_<Ex…​>, where each of the Ex types derives from std::exception (in this case, please also #include <boost/leaf/handle_exception.hpp>);

    • may take an error_info argument by const &;

    • may take a diagnostic_info argument by const &;

    • may take a verbose_diagnostic_info argument by const &;

    • may not take any other types of arguments.

    • Must return a type that can be used to initialize an object of the type R; in case R is a result<void> (that is, in case of success it does not communicate a value), handlers that return void are permitted. If such a handler matches the failure, the try_handle_some return value is initialized by {}.

Effects:
  • Creates a local context<E…​> object ctx, where the E…​ types are automatically deduced from the types of arguments taken by each h…​, which guarantees that it is able to store all of the types required to handle errors.

  • Invokes the try_block:

    • if the returned object r indicates success, it is forwarded to the caller.

    • otherwise, LEAF considers each of the h…​ handlers, in order, until it finds one that matches the reported r.error(). The first matching handler is invoked and its return value is used to initialize the return value of try_handle_some, which can indicate success if the handler was able to handle the error, or failure if it was not.

    • if try_handle_some is unable to find a matching handler, it returns r.

try_handle_some is exception-neutral: it does not throw exceptions, however the user-supplied handlers are permitted to throw.
Handler Matching Procedure:

A handler h matches the failure reported by r iff try_handle_some is able to produce values to pass as its arguments, using the E-types stored in ctx, associated with the error ID obtained by calling r.error(). As soon as it is determined that an argument value can not be produced, the current handler is dropped and the matching procedure continues with the next handler, if any.

The return value of r.error() must be implicitly convertible to error_id. Naturally, the leaf::result template satisfies this requirement. If an external result type is used instead, usually r.error() would return a std::error_code, which is able to communicate LEAF error IDs; see Interoperability.

If err is the error ID obtained from r.error(), each argument value ai to be passed to the handler currently under consideration is produced as follows:

  • If ai is taken as Ai const & or by value:

    • If an E-object of type Ai, associated with err, is currently stored in ctx, ai is initialized with a reference to the stored object; otherwise the handler is dropped.

      Example:
      ....
      auto r = leaf::try_handle_some(
        []
        {
          return f(); // returns leaf::result<int>
        },
      
        []( leaf::e_file_name const & fn ) (1)
        {
          std::cerr << "File Name: \"" << fn.value << '"' << std::endl; (2)
          return 1;
        } );
      1 In case the try_block (the first lambda) indicates a failure, this handler will be matched if ctx stores an e_file_name associated with the error. Because this is the only supplied handler, if an e_file_name is not available, try_handle_some will return the leaf::result<int> returned by f.
      2 Print the file name, handle the error.
    • If Ai is of the predicate type match<E,V…​>, if an object of type E, associated with err, is currently stored in ctx, ai is initialized with a reference to the stored object; otherwise the handler is dropped. The handler is also dropped if the expression ai() evaluates to false (see match<E,V…​>).

      Example:
      enum class errors
      {
        ec1=1,
        ec2,
        ec3
      };
      
      ....
      
      try_handle_some(
        []
        {
          return f();
        },
      
        []( leaf::match<errors, errors::ec1> ) (1)
        {
          ....
        },
      
        []( errors ec ) (2)
        {
          ....
        } );
      }
      1 This handler is matched if the error includes an object of type errors with value ec1.
      2 This handler is matched if the error includes an object of type errors regardless of its value.

      In particular, the E type used to instantiate the match template may be an instance of the condition class template, which is used to match a std::error_condition enumerated value:

      Example:
      enum class cond_x { x00, x11, x22, x33 };
      
      namespace std { template <> struct is_error_condition_enum<cond_x>: true_type { }; };
      
      ....
      
      try_handle_some(
        []
        {
          return f();
        },
      
        [&c]( leaf::match<leaf::condition<cond_x>, cond_x::x11> ) (1)
        {
          ....
        },
      
        []( std::error_code const & ec ) (2)
        {
          ....
        } );
      }
      1 This handler is matched if the error includes an object of type std::error_code equivalent to the error condition cond_x::x11.
      2 This handler is matched if the error includes any object of type std::error_code.
    • If Ai is of the predicate type catch_<Ex…​>, and the try_block throws, ai is initialized with the current std::exception. The handler is dropped if the expression ai() evaluates to false (see catch_<Ex…​>).

      Example:
      struct exception1: std::exception { };
      struct exception2: std::exception { };
      struct exception3: std::exception { };
      
      ....
      
      try_handle_some(
        []
        {
          return f(); // throws
        },
      
        []( leaf::catch_<exception1, exception2> ) (1)
        {
          ....
        },
      
        []( leaf::error_info const & info ) (2)
        {
          ....
        } );
      1 This handler is matched if the current exception is either of type exception1 or exception2.
      2 This handler is matched any error. Use info.exception() to access the caught std::exception object.
      Using catch_ requires #include <boost/leaf/handle_exception.hpp>.
  • If ai is of type Ai const *, try_handle_some is always able to produce it: first it attempts to match it as if it is taken by const &; if that fails, ai is initialized with 0.

    Example:
    ....
    try_handle_some(
      []
      {
        return f(); // throws
      },
    
      []( leaf::e_file_name const * fn ) -> leaf::result<void> (1)
      {
        if( fn ) (2)
          std::cerr << "File Name: \"" << fn->value << '"' << std::endl;
      } );
    }
    1 This handler matches any error, because it takes e_file_name as a const * (and nothing by const &).
    2 If an e_file_name is available with the current error, print it.
  • If ai is of type error_info const &, try_handle_some is always able to produce it.

    Example:
    ....
    try_handle_some(
      []
      {
        return f(); // returns leaf::result<T>
      },
    
      []( leaf::error_info const & info ) (1)
      {
        std::cerr << "leaf::error_info:" << std::endl << info; (2)
        return info.error(); (3)
      } );
    1 This handler matches any error.
    2 Print error information.
    3 Return the original error, which will be returned out of try_handle_some.
  • If ai is of type diagnostic_info const &, try_handle_some is always able to produce it.

    Example:
    ....
    try_handle_some(
      []
      {
        return f(); // throws
      },
    
      []( leaf::diagnostic_info const & info ) (1)
      {
        std::cerr << "leaf::diagnostic_information:" << std::endl << info; (2)
        return info.error(); (3)
      } );
    1 This handler matches any error.
    2 Print diagnostic information, including limited information about dropped error objects.
    3 Return the original error, which will be returned out of try_handle_some.
  • If ai is of type verbose_diagnostic_info const &, try_handle_some is always able to produce it.

    Example:
    ....
    try_handle_some(
      []
      {
        return f(); // throws
      },
    
      []( leaf::verbose_diagnostic_info const & info ) (1)
      {
        std::cerr << "leaf::verbose_diagnostic_information:" << std::endl << info; (2)
        return info.error(); (3)
      } );
    1 This handler matches any error.
    2 Print verbose diagnostic information, including values of dropped error objects.
    3 Return the original error, which will be returned out of try_handle_some.

Reference: Types

The contents of each Reference section are organized alphabetically.

augment_id

namespace boost { namespace leaf {

  class augment_id
  {
  public:

    augment_id() noexcept;

    error_id check_error() const noexcept;

    template <class... E>
    error_id get_error( E && ... e ) const noexcept;
  };

} }

This class helps obtain an error_id to associate error objects with, when augmenting failures communicated using LEAF through uncooperative APIs that do not use LEAF to report errors.

The common usage of this class is as follows:

error_code compute_value( int * out_value ) noexcept; (1)

leaf::error<int> augmenter() noexcept
{
  leaf::augment_id augment; (2)

  int val;
  auto ec = compute_value(&val);

  if( failure(ec) )
    return augment.get_error(e1, e2, ...); (3)
  else
    return val; (4)
}
1 Uncooperative third-party API that does not use LEAF, but results in calling a user callback that does use LEAF. In case our callback reports a failure, we’ll augment it with error objects available in the calling scope, even though compute_value can not communicate an error_id.
2 Initialize an augment_id object.
3 The call to compute_value has failed:
  • If new_error was invoked (by the calling thread) after the augment object was initialized, get_error returns the last error_id returned by new_error. This would be the case if the failure originates in our callback (invoked internally by compute_value).

  • Else, get_error invokes new_error and returns that error_id.

4 The call was successful, return the computed value.

The check_error function works similarly, but instead of invoking new_error it returns a defaul-initialized error_id.


catch_

namespace boost { namespace leaf {

  template <class... Ex>
  struct catch_
  {
    std::exception const & value;

    explicit catch_( std::exception const & ex ) noexcept;

    bool operator()() const noexcept;
  };

} }
The catch_ template is useful only as an argument to a handler function passed to a LEAF error-handling function.
Effects:

The catch_ constructor initializes the value reference with ex.

The catch_ template is a predicate function type: operator() returns true iff for at least one of Exi in Ex…​, the expression dynamic_cast<Exi const *>(&value) != 0 is true.

Example:
struct exception1: std::exception { };
struct exception2: std::exception { };
struct exception3: std::exception { };

exception2 x;

catch_<exception1> c1(x);
assert(!c1());

catch_<exception2> c2(x);
assert(c2());

catch_<exception1,exception2> c3(x);
assert(c3());

catch_<exception1,exception3> c4(x);
assert(!c4());
See Five Minute Introduction Using Exception Handling.

condition

namespace boost { namespace leaf {

  template <class Enum, class ErrorConditionEnum = Enum>
  struct condition;

} }
The condition template is useful only as argument to the match template, to match a specific std::error_condition.
Example:
enum class cond_x { x00, x11, x22, x33 };

namespace std { template <> struct is_error_condition_enum<cond_x>: true_type { }; };

std::error_code ec;
match<condition<cond_x, cond_x::x11>> m(ec);

// m() evaluates to true if ec is equivalent to the error condition cond_x::x11.
See also match.

context

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  class context
  {
    context( context const & ) = delete;
    context & operator=( context const & ) = delete;

  public:

    context() noexcept;
    context( context && x ) noexcept;
    ~context() noexcept;

    void activate() noexcept;
    void deactivate() noexcept;
    bool is_active() const noexcept = 0;

    void propagate() noexcept = 0;

    void print( std::ostream & os ) const;

    template <class R, class... H>
    R handle_error( error_id, H && ... ) const;

    template <class R, class RemoteH>
    R remote_handle_error( error_id, RemoteH && ) const;

  };

  template <class RemoteH>
  using context_type_from_remote_handler = typename <<unspecified>>::type;

} }

The context class template provides storage for each of the specified E-types. Typically, context objects are not used directly; they’re created internally when the try_handle_some, try_handle_all or try_catch functions are called, instantiated with E-types automatically deduced from the arguments of the passed handlers.

Independently, users can create context objects if they need to capture E-objects and then transport them, by moving the context object itself.

Even in that case it is recommended that users do not instantiate the context template by explicitly listing the E-types they want it to be able to store. Instead, use context_type_from_remote_handler or call the make_context function template, which deduce the correct E-types from a captured list of handler function objects.

To be able to load up error objects in a context object, it must be activated. Activating a context object ctx binds it to the calling thread, setting thread-local pointers of the stored E…​ types to point to the corresponding storage within ctx. It is possible, even likely, to have more than one active context in any given thread. In this case, activation/deactivation must happen in a LIFO manner. For this reason, it is best to use a context_activator, which relies on RAII to activate and deactivate a context.

When a context is deactivated, it detaches from the calling thread, restoring the thread-local pointers to their pre-activate values. Typically, at this point the stored E-objects, if any, are either discarded (by default) or moved to corresponding storage in other context objects active in the calling thread (if available), by calling propagate.

While error handling typically uses try_handle_some, try_handle_all or try_catch, it is also possible to handle errors by calling the member functions handle_error and remote_handle_error. They take an error_id, and attempt to match an error handler with E-objects stored in *this.

context objects can be moved, as long as they aren’t active. Moving an active context results in undefined behavior.

Constructors

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  context<E...>::context() noexcept;

  template <class... E>
  context<E...>::context( context && x ) noexcept;

} }

The default constructor initializes an empty context object: it provides storage for, but does not contain any E-objects.

The move constructor moves the stored E-objects from one context to the other.

Moving an active context object results in undefined behavior.

activate

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  void context<E...>::activate() noexcept;

} }
Preconditions:

!is_active().

Effects:

Associates *this with the calling thread.

Ensures:

is_active().

When a context is associated with a thread, thread-local pointers are set to point each E-type in its store, while the previous value of each such pointer is preserved in the context object, so that the effect of activate can be undone by calling deactivate.

When an E-object is loaded, it is moved in the last activated (in the calling thread) context object that provides storage for that E-type (note that this may or may not be the last activated context object). If no such storage is available, the E-object is discarded.


deactivate

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  void context<E...>::deactivate() noexcept;

} }
Preconditions:
  • is_active();

  • *this must be the last activated context object in the calling thread.

Effects:

De-associates *this with the calling thread.

Ensures:

!is_active().

When a context is deactivated, the thread-local pointers that currently point to each individual E-object storage in it are restored to their original value prior to calling activate.


handle_error

#include <boost/leaf/handle_error.hpp>
namespace boost { namespace leaf {

  template <class... E>
  template <class R, class... H>
  R context<E...>::handle_error( error_id err, H && ... h ) const;

} }

This function works similarly to try_handle_all, but rather than calling a try_block and obtaining the error_id from the returned result type, it matches error objects (stored in *this, associated with err) with a suitable error handler from the h…​ pack.

The caller is required to specify the return type R. This is because in general the supplied handlers may return different types (which must all be convertible to R).

is_active

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  bool context<E...>::is_active() const noexcept;

} }
Returns:

true if the *this is active in any thread, false otherwise.


print

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  void context<E...>::print( std::ostream & os ) const;

} }
Effects:

Prints all E-objects currently stored in *this, together with the unique error ID each individual E-object is associated with.


propagate

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  template <class... E>
  void context<E...>::propagate() noexcept;

} }
Preconditions:

is_active() or *this must be the last deactivated context object in the calling thread. That is, it is valid to call propagate while is_active() is true, or immediately after calling deactivate().

Effects:

Each stored E-object is moved to the storage (within other active context objects) pointed by the corresponding thread-local pointer, captured when *this was activated — or discarded, if the corresponding thread-local pointer is null.


remote_handle_error

#include <boost/leaf/handle_error.hpp>
namespace boost { namespace leaf {

  template <class... E>
  template <class R, class RemoteH>
  R context<E...>::remote_handle_error( R &, RemoteH && ) const;

} }

This function works similarly to remote_try_handle_all, but rather than calling a try_block and obtaining the error_id from the returned result type, it matches error objects (stored in *this, associated with err) with a suitable error handler from the h…​ pack.

The caller is required to specify the return type R. This is because in general the supplied handlers may return different types (which must all be convertible to R).

context_activator

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  template <class Ctx>
  class context_activator
  {
    context_activator( context_activator const & ) = delete;
    context_activator & operator=( context_activator const & ) = delete;

  public:

    explicit context_activator( Ctx & ctx ) noexcept;
    context_activator( context_activator && ) noexcept;
    ~context_activator() noexcept;
  };

} }

context_activator is a simple class that activates and deactivates a context using RAII:

If ctx.is_active() is true at the time the context_activator is initialized, the constructor and the destructor have no effects. Otherwise:

  • The constructor stores a reference to ctx in *this and calls ctx.activate().

  • The destructor:

    • Has no effects if ctx.is_active() is false (that is, it is valid to call deactivate manually, before the context_activator object expires);

    • Otherwise, calls ctx.deactivate() and, if there are new uncaught exceptions since the constructor was called, the destructor calls ctx.propagate().

For automatic deduction of Ctx, use activate_context.


diagnostic_info

namespace boost { namespace leaf {

  class diagnostic_info: public error_info
  {
    //Constructors unspecified

    friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x );
  };

} }

Handlers passed to try_handle_some, try_handle_all or try_catch may take an argument of type diagnostic_info const & if they need to print diagnostic information about the error.

The message printed by operator<< includes the message printed by error_info, followed by basic information about E-objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active context (these E-objects were discarded by LEAF, because no handler needed them).

The additional information is limited to the type name of the first such E-object, as well as their total count.

The behavior of diagnostic_info (and verbose_diagnostic_info) is affected by the value of the macro LEAF_DIAGNOSTICS:

  • If it is 1 (the default), LEAF produces diagnostic_info but only if an active error handling context on the call stack takes an argument of type diagnostic_info;

  • If it is 0, the diagnostic_info functionality is stubbed out even for error handling contexts that take an argument of type diagnostic_info. This could shave a few cycles off the error path in some programs.


error_id

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  class error_id
  {
  public:

    error_id() noexcept;

    error_id( std::error_code const & ec ) noexcept;

    int value() const noexcept;
    explicit operator bool() const noexcept;

    std::error_code to_error_code() const noexcept;

    friend bool operator==( error_id a, error_id b ) noexcept;
    friend bool operator!=( error_id a, error_id b ) noexcept;
    friend bool operator<( error_id a, error_id b ) noexcept;

    template <class... E>
    error_id load( E && ... e ) const noexcept;

    template <class... F>
    error_id accumulate( F && ... f ) const noexcept;

    friend std::ostream & operator<<( std::ostream & os, error_id x );
  };

  bool is_error_id( std::error_code const & ec ) noexcept;

  template <class... E>
  error_id new_error( E && ... e ) noexcept;

  error_id current_error() noexcept;

} }

Values of type error_id identify a specific occurrence of an error condition across the entire program. They can be copied, moved, assigned to, and compared to other error_id objects. They’re as efficient as an int.


Constructors

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  error_id::error_id() noexcept = default;

  error_id::error_id( std::error_code const & ec ) noexcept;

} }

A default-initialized error_id object does not represent an error condition. It compares equal to any other default-initialized error_id object. All other error_id objects identify a specific occurrence of a failure.

Converting an error_id object to std::error_code uses an unspecified std::error_category which LEAF recognizes. This allows an error_id to be transported through interfaces that work with std::error_code. There is an error_id constructor that allows the original error_id to be restored.

To check if a given std::error_code is actually carrying an error_id, use is_error_id.

Typically, users create new error_id objects by invoking new_error. The constructor that takes std::error_code has the following effects:

  • If ec.value() is 0, the effect is the same as using the default constructor.

  • Otherwise, if is_error_id(ec) is true, the original error_id value is used to initialize *this;

  • Otherwise, *this is initialized by the value returned by new_error, while ec is passed to load, enclosed in an unspecified E-type, which enables handlers used with try_handle_some, try_handle_all or try_catch to receive it as an argument of type std::error_code (or match<condition>).


accumulate

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  template <class... F>
  error_id error_id::accumulate( F && ... f ) const noexcept;

} }
Requirements:

Each f must be a function type that takes a single E-type argument by l-value reference.

Effects:

Similar to load, but rather than loading E-types, it calls each fi with the matching E-type object currently stored in an active context; see Accumulation.

Returns:

*this.


is_error_id

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  bool is_error_id( std::error_code const & ec ) noexcept;

} }
Returns:

true if ec uses the LEAF-specific std::error_category that identifies it as carrying an error ID rather than another error code; otherwise returns false.


load

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  template <class... E>
  error_id error_id::load( E && ... e ) const noexcept;

} }
Effects:
  • If value()!=0, each of the e…​ objects is loaded and uniquely associated with *this.

  • Otherwise all e…​ objects are discarded.

Returns:

*this.


operator==, !=, <

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

  friend bool operator==( error_id a, error_id b ) noexcept;
  friend bool operator!=( error_id a, error_id b ) noexcept;
  friend bool operator<( error_id a, error_id b ) noexcept;

} }

These functions have the usual semantics, comparing a.value() and b.value().


operator bool

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

    explicit error_id::operator bool() const noexcept;

} }
Effects:

As if return value()!=0.


to_error_code

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

    std::error_code error_id::to_error_code() const noexcept;

} }
Effects:

Returns a std::error_object with the same value() as *this, using an unspecified std::error_category.

The returned object can be used to initialize an error_id, in which case the original error_id value will be restored.
Use is_error_id to check if a given std::error_code carries an error_id.

value

#include <boost/leaf/error.hpp>
namespace boost { namespace leaf {

    int error_id::value() const noexcept;

} }
Effects:
  • If *this was initialized using the default constructor, returns 0.

  • Otherwise returns an int, a program-wide unique identifier of the failure.


e_api_function

namespace boost { namespace leaf {

  struct e_api_function {char const * value;};

} }

The e_api_function type is designed to capture the name of the API function that failed. For example, if you’re reporting an error from fread, you could use leaf::e_api_function {"fread"}.

The passed value is stored as a C string (char const *), so value should only be initialized with a string literal.

e_at_line

namespace boost { namespace leaf {

  struct e_at_line { int value; };

} }

e_at_line can be used to communicate the line number when reporting errors (for example parse errors) about a text file.


e_errno

namespace boost { namespace leaf {

  struct e_errno
  {
    int value;
    friend std::ostream & operator<<( std::ostream & os, e_errno const & err );
  };

} }

To capture errno, use e_errno. When printed in automatically-generated diagnostic messages, e_errno objects use strerror to convert the errno code to string.


e_file_name

namespace boost { namespace leaf {

  struct e_file_name {std::string value;};

} }

When a file operation fails, you could use e_file_name to store the name of the file.


e_LastError

namespace boost { namespace leaf {

  namespace windows
  {
    struct e_LastError
    {
      unsigned value;
      friend std::ostream & operator<<( std::ostream & os, e_LastError const & err );
    };
  }

} }

e_LastError is designed to communicate GetLastError() values on Windows.


e_source_location

namespace boost { namespace leaf {

  struct e_source_location
  {
    char const * const file;
    int const line;
    char const * const function;

    friend std::ostream & operator<<( std::ostream & os, e_source_location const & x );
  };

} }

The LEAF_NEW_ERROR, LEAF_EXCEPTION and LEAF_THROW macros capture __FILE__, __LINE__ and __FUNCTION__ into a e_source_location object.


e_type_info_name

namespace boost { namespace leaf {

  struct e_type_info_name { char const * value; };

} }

e_type_info_name is designed to store the return value of std::type_info::name.


error_info

namespace boost { namespace leaf {

  class error_info
  {
    //Constructors unspecified

  public:

    error_id error() const noexcept;

    bool exception_caught() const noexcept;
    std::exception const * exception() const noexcept;

    friend std::ostream & operator<<( std::ostream & os, error_info const & x );
  };

} }

Handlers passed to error-handling functions such as try_handle_some, try_handle_all or try_catch may take an argument of type error_info const & to receive information about the error.

The error member function returns the program-wide unique error_id of the error.

The exception_caught member function returns true if the handler that received *this is being invoked to handle an exception, false otherwise.

If handling an exception, the exception member function returns a pointer to the std::exception subobject of the caught exception, or 0 if that exception could not be converted to std::exception. It is illegal to call exception unless exception_caught() is true.

The operator<< overload prints diagnostic information about each E-object currently stored in the context local to the try_handle_some, try_handle_all or try_catch scope that invoked the handler, but only if it is associated with the error_id returned by error().


match

namespace boost { namespace leaf {

  template <class E, typename deduced-type<E>::type... V>
  class match
  {
  public:

    using type = typename unspecified-deduction<E>::type;

    explicit match( type const * value ) noexcept;

    explicit bool operator()() const noexcept;

    type const & value() const noexcept;
  };

} }
Effects:
  • If E is an instance of the condition template:

    • The type of the parameter pack V…​ is deduced as the type of the error condition enum used with condition;

    • match<E>::type is deduced as std::error_code;

    • The boolean conversion operator evaluates to true iff the std::error_code pointer passed to the constructor is not 0 and matches one of the error condition enum values used with condition.

  • Otherwise, if E defines an accessible data member value:

    • The type of the parameter pack V…​ and match<E>::type are deduced as decltype(std::declval<E>().value);

    • The boolean conversion operator evaluates to true iff the value passed to the constructor is not 0 and is equal to one of V…​.

  • Otherwise:

    • The type of the parameter pack V…​ and match<E>::type are deduced as E;

    • The boolean conversion operator evaluates to true iff the value passed to the constructor is not 0 and is equal to one of V…​.

The examples below demonstrate how match works in isolation, but it is designed to be used as argument to a handler function passed to an error-handling function such as try_handle_some, try_handle_all, try_catch. See Five Minute Introduction Using result<T> for a more practical example.
Example 1:
struct error_code { int value; };

error_code e = {42};

match<error_code, 1> m1(e);
assert(!m1());

match<error_code, 42> m2(e);
assert(m2());

match<error_code, 1, 5, 42, 7> m3(e);
assert(m3());

match<error_code, 1, 3, -42> m4(e);
assert(!m4());
Example 2:
enum error_code { e1=1, e2, e3 };

error_code e = e2;

match<error_code, e1> m1(e);
assert(!m1());

match<error_code, e2> m2(e);
assert(m2());

match<error_code, e1, e2> m3(e);
assert(m3());

match<error_code, e1, e3> m4(e);
assert(!m4());

polymorphic_context

#include <boost/leaf/context.hpp>
namespace boost { namespace leaf {

  class polymorphic_context
  {
  protected:

    polymorphic_context() noexcept;
    ~polymorphic_context() noexcept;

  public:

    virtual void activate() noexcept = 0;
    virtual void deactivate() noexcept = 0;
    virtual bool is_active() const noexcept = 0;

    virtual void propagate() noexcept = 0;

    virtual void print( std::ostream & ) const = 0;
  };

} }

The polymorphic_context class is an abstract base type which can be used to erase the type of the exact instantiation of the context class template used. See make_shared_context.


result

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  class result
  {
  public:

    result() noexcept;
    result( T && v ) noexcept;
    result( T const & v );

    result( error_id err ) noexcept;
    result( std::error_code const & ec ) noexcept;
    result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;

    result( result && r ) noexcept;

    template <class U>
    result( result<U> && r ) noexcept;

    result & operator=( result && r ) noexcept;

    template <class U>
    result & operator=( result<U> && r ) noexcept;

    explicit operator bool() const noexcept;

    T const & value() const;
    T & value();

    T const & operator*() const;
    T & operator*();

    T const * operator->() const;
    T * operator->();

    <<unspecified-type>> error() noexcept;

    template <class... E>
    error_id load( E && ... e ) noexcept;

    template <class... F>
    error_id accumulate( F && ... f );
  };

  struct bad_result: std::exception { };

} }

The result<T> type can be returned by functions which produce a value of type T but may fail doing so.

Requirements:

T must be movable, and its move constructor may not throw.

Invariant:

A result<T> object is in one of three states:

  • Value state, in which case it contains an object of type T, and value/operator*/operator-> can be used to access the contained value.

  • Error state, in which case it contains an error ID, and calling value/operator*/operator-> throws leaf::bad_result.

  • Error-capture state, which is the same as the Error state, but in addition to the error ID, it holds a std::shared_ptr<polymorphic_context>.

result<T> objects are nothrow-moveable but are not copyable.


Constructors

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  result<T>::result() noexcept;

  template <class T>
  result<T>::result( T && v ) noexcept;

  template <class T>
  result<T>::result( leaf::error_id err ) noexcept;

  template <class T>
  result<T>::result( std::error_code const & ec ) noexcept;

  template <class T>
  result<T>::result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;

  template <class T>
  result<T>::result( result && ) noexcept;

  template <class T>
  template <class U>
  result<T>::result( result<U> && ) noexcept;

} }
Requirements:

T must be movable, and its move constructor may not throw.

Effects:

Establishes the result<T> invariant:

When a result object is initialized with a std::error_code object, it is used to initialize an error_id object, then the behavior is the same as if initialized with error_id.

Throws:
  • Initializing the result<T> in Value state may throw, depending on which constructor of T is invoked;

  • Other constructors do not throw.

A result that is in value state converts to true in boolean contexts. A result that is not in value state converts to false in boolean contexts.
result<T> objects are nothrow-moveable but are not copyable.

accumulate

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  template <class... F>
  error_id result<T>::accumulate( F && ... f );

} }

This member function is designed for use in return statements in functions that return result<T> to forward accumulated E-objects to the caller.

Effects:

As if error_id(this->error()).accumulate(std::forward<F>(f)…​).

Returns:

*this.


error

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class... E>
  <<unspecified-type>> result<T>::error() noexcept;

} }

Returns: A proxy object of unspecified type, implicitly convertible to any instance of the result class template, as well as to error_id.

  • If the proxy object is converted to some result<U>:

    • If *this is in Value state, returns result<U>(error_id()).

    • Otherwise the state of *this is moved into the returned result<U>.

  • If the proxy object is converted to an error_id:

  • If the proxy object is not used, the state of *this is not modified.

The returned proxy object refers to *this; avoid holding on to it.

load

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  template <class... E>
  error_id result<T>::load( E && ... e ) noexcept;

} }

This member function is designed for use in return statements in functions that return result<T> to forward additional E-objects to the caller.

Effects:

As if error_id(this->error()).load(std::forward<E>(e)…​).

Returns:

*this.


operator=

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  result<T> & result<T>::operator=( result && ) noexcept;

  template <class T>
  template <class U>
  result<T> & result<T>::operator=( result<U> && ) noexcept;

} }
Effects:

Destroys *this, then re-initializes it as if using the appropriate result<T> constructor. Basic exception-safety guarantee.


operator bool

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  result<T>::operator bool() const noexcept;

} }
Returns:

If *this is in value state, returns true, otherwise returns false.


value / operator* / operator->

#include <boost/leaf/result.hpp>
namespace boost { namespace leaf {

  template <class T>
  T const & result<T>::value() const;

  template <class T>
  T & result<T>::value();

  template <class T>
  T const & result<T>::operator*() const;

  template <class T>
  T & result<T>::operator*();

  template <class T>
  T const * result<T>::operator->() const;

  template <class T>
  T * result<T>::operator->();

  struct bad_result: std::exception { };

} }
Effects:

If *this is in value state, returns a reference (or pointer) to the stored value, otherwise throws bad_result.


verbose_diagnostic_info

namespace boost { namespace leaf {

  class verbose_diagnostic_info: public error_info
  {
    //Constructors unspecified

    friend std::ostream & operator<<( std::ostream & os, verbose_diagnostic_info const & x );
  };

} }

Handlers passed to error-handling functions such as try_handle_some, try_handle_all or try_catch may take an argument of type verbose_diagnostic_info const & if they need to print diagnostic information about the error.

The message printed by operator<< includes the message printed by error_info, followed by information about E-objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active context (these E-objects were discarded by LEAF, because no handler needed them).

The additional information includes the types and the values of all such E-objects.

The behavior of verbose_diagnostic_info (and diagnostic_info) is affected by the value of the macro LEAF_DIAGNOSTICS:

  • If it is 1 (the default), LEAF produces verbose_diagnostic_info but only if an active error handling context on the call stack takes an argument of type verbose_diagnostic_info;

  • If it is 0, the verbose_diagnostic_info functionality is stubbed out even for error handling contexts that take an argument of type verbose_diagnostic_info. This could save some cycles on the error path in some programs.

Using verbose_diagnostic_info will likely allocate memory dynamically.

Reference: Macros

The contents of each Reference section are organized alphabetically.

LEAF_AUTO

#include <boost/leaf/result.hpp>
#define LEAF_AUTO(v,r)\
  auto && _r_##v = r;\
  if( !_r_##v )\
    return _r_##v.error();\
  auto & v = _r_##v.value()

LEAF_AUTO is useful when calling a function that returns result<T> (other than result<void>), if the desired behavior is to forward any errors to the caller verbatim.

Example:

Compute two int values, return their sum as a float, using LEAF_AUTO:
leaf::result<int> compute_value();

leaf::result<float> add_values()
{
  LEAF_AUTO(v1, compute_value());
  LEAF_AUTO(v2, compute_value());
  return v1 + v2;
}

Of course, we could write add_value without using LEAF_AUTO. This is equivalent:

Compute two int values, return their sum as a float, without LEAF_AUTO:
leaf::result<float> add_values()
{
  auto v1 = compute_value();
  if( !v1 )
    return v1.error();

  auto v2 = compute_value();
  if( !v2 )
    return v2.error();

  return v1.value() + v2.value();
}

LEAF_CHECK

#include <boost/leaf/result.hpp>
#define LEAF_CHECK(r)\
  {\
    auto && _r = r;\
    if(!_r)\
      return _r.error();\
  }

LEAF_CHECK is useful when calling a function that returns result<void>, if the desired behavior is to forward any errors to the caller verbatim.

Example:

Try to send a message, then compute a value, report errors using LEAF_CHECK:
leaf::result<void> send_message( char const * msg );

leaf::result<int> compute_value();

leaf::result<int> say_hello_and_compute_value()
{
  LEAF_CHECK(send_message("Hello!"));
  return compute_value();
}

Equivalent implementation without LEAF_CHECK:

Try to send a message, then compute a value, report errors without LEAF_CHECK:
leaf::result<float> add_values()
{
  auto r = send_message("Hello!");
  if( !r )
    return r.error();

  return compute_value();
}

LEAF_NEW_ERROR

#include <boost/leaf/result.hpp>
#define LEAF_NEW_ERROR(...) <<unspecified>>
Effects:

LEAF_NEW_ERROR(e…​) is equivalent to leaf::new_error(e…​), except the current source location is automatically passed to new_error in a e_source_location object (in addition to all e…​ objects).


LEAF_EXCEPTION

#include <boost/leaf/exception.hpp>
#define LEAF_EXCEPTION(...) <<unspecified>>
Effects:

This is a variadic macro which forwards its arguments to the function template exception, in addition capturing __FILE__, __LINE__ and __FUNCTION__, in a e_source_location object.


LEAF_THROW

#include <boost/leaf/exception.hpp>
#define LEAF_THROW(...) throw LEAF_EXCEPTION(__VA_ARGS__)
Effects:

Throws the exception object returned by LEAF_EXCEPTION.

Design

Rationale

Definition:

Objects that carry information about error conditions are called error objects. For example, objects of type std::error_code are error objects.

The following reasoning is independent of the mechanism used to transport error objects, whether it is exception handling or anything else.
Definition:

Depending on their interaction with error objects, functions can be classified as follows:

  • Error-initiating: functions that initiate error conditions by creating new error objects.

  • Error-neutral: functions that forward to the caller error objects communicated by lower-level functions they call.

  • Error-handling: functions that dispose of error objects they have received, recovering normal program operation.

A crucial observation is that error-initiating functions are typically low-level functions that lack any context and can not determine, much less dictate, the correct program behavior in response to the errors they may initiate. Error conditions which (correctly) lead to termination in some programs may (correctly) be ignored in others; yet other programs may recover from them and resume normal operation.

The same reasoning applies to error-neutral functions, but in this case there is the additional issue that the errors they need to communicate, in general, are initiated by functions multiple levels removed from them in the call chain, functions which usually are — and should be treated as — implementation details. An error-neutral function should not be coupled with error object types communicated by error-initiating functions, for the same reason it should not be coupled with any other aspect of their interface.

Finally, error-handling functions, by definition, have the full context they need to deal with at least some, if not all, failures. In their scope it is an absolute necessity that the author knows exactly what information must be communicated by lower level functions in order to recover from each error condition. Specifically, none of this necessary information can be treated as implementation details; in this case, the coupling which is to be avoided in error-neutral functions is in fact desirable.

We’re now ready to define our

Design goals:
  • Error-initiating functions should be able to communicate all information available to them that is relevant to the failure being reported.

  • Error-neutral functions should not be coupled with error types communicated by lower-level error-initiating functions. They should be able to augment any failure with additional relevant information available to them.

  • Error-handling functions should be able to access all the information communicated by error-initiating or error-neutral functions that is needed in order to deal with failures.

The design goal that error-neutral functions are not coupled with the static type of error objects that pass through them seems to require dynamic polymorphism and therefore dynamic memory allocations (the Boost Exception library meets this design goal at the cost of dynamic memory allocation).

As it turns out, dynamic memory allocation is not necessary due to the following

Fact:
  • Error-handling functions "know" which of the information error-initiating and error-neutral functions are able to communicate is actually needed in order to deal with failures in a particular program. Ideally, no resources should be used wasted storing or communicating information which is not currently needed to handle errors, even if it is relevant to the failure.

For example, if a library function is able to communicate an error code but the program does not need to know the exact error code, then that information may be ignored at the time the library function attempts to communicate it. On the other hand, if an error-handling function needs that information, the memory needed to store it can be reserved statically in its scope.

The LEAF functions try_handle_some, try_handle_all and try_catch implement this idea. Users provide error-handling lambda functions, each taking arguments of the types it needs in order to recover from a particular error condition. LEAF simply provides the space needed to store these types (in the form of a std::tuple, using automatic storage duration) until they are passed to a matching handler.

At the time this space is reserved in the scope of an error-handling function, thread_local pointers of the required error types are set to point to the corresponding objects within it. Later on, error-initiating or error-neutral functions wanting to communicate an error object of a given type E use the corresponding thread_local pointer to detect if there is currently storage available for this type:

  • If the pointer is not null, storage is available and the object is moved into the pointed storage, exactly once — regardless of how many levels of function calls must unwind before an error-handling function is reached.

  • If the pointer is null, storage is not available and the error object is discarded, since no error-handling function makes any use of it in this program — saving resources.

This almost works, except we need to make sure that error-handling functions are protected from accessing stale error objects stored in response to previous failures, which would be a serious logic error. To this end, each occurrence of an error is assigned a unique error_id. Each of the E…​ objects stored in error-handling scopes is assigned an error_id as well, permanently associating it with a particular failure.

Thus, to handle a failure we simply match the available error objects (associated with its unique error_id) with the argument types required by each user-provided error-handling function. In terms of C++ exception handling, it is as if we could write something like:

try
{
  auto r = process_file();

  //Success, use r:
  ....
}

catch( file_read_error const &, e_file_name const & fn, e_errno const & err )
{
  std::cerr <<
    "Could not read " << fn << ", errno=" << err << std::endl;
}

catch( file_read_error const &, e_errno const & err )
{
  std::cerr <<
    "File read error, errno=" << err << std::endl;
}

catch( file_read_error const & )
{
  std::cerr << "File read error!" << std::endl;
}

Of course this syntax is not valid, so LEAF uses lambda functions to express the same idea:

leaf::try_catch(

  []
  {
    auto r = process_file(); //Throws in case of failure, E-objects stored inside the try_catch scope

    //Success, use r:
    ....
  }

  []( leaf::catch_<file_read_error>, e_file_name const & fn, e_errno const & err )
  {
    std::cerr <<
      "Could not read " << fn << ", errno=" << err << std::endl;
  },

  []( leaf::catch_<file_read_error>, e_errno const & err )
  {
    std::cerr <<
      "File read error, errno=" << err << std::endl;
  },

  []( leaf::catch_<file_read_error> )
  {
    std::cerr << "File read error!" << std::endl;
  } );

Similar syntax works without exception handling as well. Below is the same snippet, written using result<T>:

return leaf::try_handle_some(

  []() -> leaf::result<void>
  {
    LEAF_AUTO(r, process_file()); //In case of errors, E-objects are stored inside the try_handle_some scope

    //Success, use r:
    ....

    return { };
  }

  []( leaf::match<error_enum, file_read_error>, e_file_name const & fn, e_errno const & err )
  {
    std::cerr <<
      "Could not read " << fn << ", errno=" << err << std::endl;
  },

  []( leaf::match<error_enum, file_read_error>, e_errno const & err )
  {
    std::cerr <<
      "File read error, errno=" << err << std::endl;
  },

  []( leaf::match<error_enum, file_read_error> )
  {
    std::cerr << "File read error!" << std::endl;
  } );
Please post questions and feedback on the Boost Developers Mailing List (LEAF is not part of Boost).

Critique 1: Error Types Do Not Participate in Function Signatures

A knee-jerk critique of the LEAF design is that it does not statically enforce that each possible error condition is recognized and handled by the program. One idea I’ve heard from multiple sources is to add E…​ parameter pack to result<T>, essentially turning it into expected<T,E…​>, so we could write something along these lines:

expected<T, E1, E2, E3> f() noexcept; (1)

expected<T, E1, E3> g() noexcept (2)
{
  if( expected<T, E1, E2, E3> r = f() )
  {
    return r; //Success, return the T
  }
  else
  {
    return r.handle_error<E2>( [] ( .... ) (3)
      {
        ....
      } );
  }
}
1 f may only return error objects of type E1, E2, E3.
2 g narrows that to only E1 and E3.
3 Because g may only return error objects of type E1 and E3, it uses handle_error to deal with E2. In case r contains E1 or E3, handle_error simply returns r, narrowing the error type parameter pack from E1, E2, E3 down to E1, E3. If r contains an E2, handle_error calls the supplied lambda, which is required to return one of E1, E3 (or a valid T).

The motivation here is to help avoid bugs in functions that handle errors that pop out of g: as long as the programmer deals with E1 and E3, he can rest assured that no error is left unhandled.

Congratulations, we’ve just discovered exception specifications. The difference is that exception specifications, before being removed from C++, were enforced dynamically, while this idea is equivalent to statically-enforced exception specifications, like they are in Java.

Why not statically enforce exception specifications?

The short answer is that nobody knows how to fix exception specifications in any language, because the dynamic enforcement C++ chose has only different (not greater or fewer) problems than the static enforcement Java chose. …​ When you go down the Java path, people love exception specifications until they find themselves all too often encouraged, or even forced, to add throws Exception, which immediately renders the exception specification entirely meaningless. (Example: Imagine writing a Java generic that manipulates an arbitrary type T).[1]
— Herb Sutter

Consider again the example above: assuming we don’t want important error-related information to be lost, values of type E1 and/or E3 must be able to encode any E2 value dynamically. But like Sutter points out, in generic contexts we don’t know what errors may result in calling a user-supplied function. The only way around that is to specify a single type (e.g. std::error_code) that can communicate any and all errors, which ultimately defeats the idea of using static type checking to enforce correct error handling.

That said, in every program there are certain error-handling functions (e.g. main) which are required to handle any error, and it is highly desirable to be able to enforce this requirement at compile-time. In LEAF, the try_handle_all function implements this idea: if the user fails to supply at least one handler that will match any error, the result is a compile error. This guarantees that the scope invoking try_handle_all is prepared to recover from any failure.


Critique 2: LEAF Does Not Facilitate Mapping Between Different Error Types

Most C++ programs use multiple C and C++ libraries, and each library may provide its own system of error codes. But because it is difficult to define static interfaces that can communicate arbitrary error code types, a popular idea is to map each library-specific error code to a common program-wide enum.

For example, if we have — 

namespace lib_a
{
  enum error
  {
    ok,
    ec1,
    ec2,
    ....
  };
}

namespace lib_b
{
  enum error
  {
    ok,
    ec1,
    ec2,
    ....
  };
}

 — we could define:

namespace program
{
  enum error
  {
    ok,
    lib_a_ec1,
    lib_a_ec2,
    ....
    lib_b_ec1,
    lib_b_ec2,
    ....
  };
}

An error-handling library could provide conversion API that uses the C++ static type system to automate the mapping between the different error enums. For example, it may define a class template result<T,E> with value-or-error variant semantics, so that:

  • lib_a errors are transported in result<T,lib_a::error>,

  • lib_b errors are transported in result<T,lib_b::error>,

  • then both are automatically mapped to result<T,program::error> once control reaches the appropriate scope.

There are several problems with this idea:

  • It is prone to errors, both during the initial implementation as well as under maintenance.

  • It does not compose well. For example, if both of lib_a and lib_b use lib_c, errors that originate in lib_c would be obfuscated by the different APIs exposed by each of lib_a and lib_b.

  • It presumes that all errors in the program can be specified by exactly one error code, which is false.

To elaborate on the last point, consider a program that attempts to read a configuration file from three different locations: in case all of the attempts fail, it should communicate each of the failures. In theory result<T,E> handles this case well:

struct attempted_location
{
  std::string path;
  error ec;
};

struct config_error
{
  attempted_location current_dir, user_dir, app_dir;
};

result<config,config_error> read_config();

This looks nice, until we realize what the config_error type means for the automatic mapping API we wanted to define: an enum can not represent a struct. It is a fact that we can not assume that all error conditions can be fully specified by an enum; an error handling library must be able to transport arbitrary static types efficiently.

While the leaf::result<T> class template does have value-or-error semantics, it does not carry the actual error objects. Instead, they are forwarded directly to the appropriate error-handling scope and their types do not participate in function signatures.

Critique 3: LEAF Does Not Treat Low Level Error Types as Implementation Details

This critique is a combination of Critique 1 and Critique 2, but it deserves special attention. Let’s consider this example using LEAF:

leaf::result<std::string> read_line( reader & r );

leaf::result<parsed_line> parse_line( std::string const & line );

leaf::result<parsed_line> read_and_parse_line( reader & r )
{
  LEAF_AUTO(line, read_line(r)); (1)
  LEAF_AUTO(parsed, parse_line(line)); (2)
  return parsed;
}
1 Read a line, forward errors to the caller.
2 Parse the line, forward errors to the caller.

The objection is that LEAF will forward verbatim the errors that are detected in read_line or parse_line to the caller of read_and_parse_line. The premise of this objection is that such low-level errors are implementation details and should be treated as such. Under this premise, read_and_parse_line should act as a translator of sorts, in both directions:

  • When called, it should translate its own arguments to call read_line and parse_line;

  • If an error is detected, it should translate the errors from the error types returned by read_line and parse_line to a higher-level type.

The motivation is to isolate the caller of read_and_parse_line from its implementation details read_line and parse_line.

There are two possible ways to implement this translation:

1) read_and_parse_line understands the semantics of all possible failures that may be reported by both read_line and parse_line, implementing a non-trivial mapping which both erases information that is considered not relevant to its caller, as well as encodes different semantics in the error it reports. In this case read_and_parse_line assumes full responsibility for describing precisely what went wrong, using its own type specifically designed for the job.

2) read_and_parse_line returns an error object that essentially indicates which of the two inner functions failed, and also transports the original error object without understanding its semantics and without any loss of information, wrapping it in a new error type.

The problem with 1) is that typically the caller of read_and_parse_line is not going to handle the error, but it does need to forward it to its caller. In our attempt to protect the one error-handling function from "implementation details", we’ve coupled the interface of all intermediate error-neutral functions with the static types of errors they do not understand and do not handle.

Consider the case where read_line communicates errno in its errors. What is read_and_parse_line supposed to do with e.g. EACCESS? Turn it into READ_AND_PARSE_LINE_EACCESS? To what end, other than to obfuscate the original (already complex and platform-specific) semantics of errno?

And what if the call to read is polymorphic, which is also typical? What if it involves a user-supplied function object? What kinds of errors does it return and why should read_and_parse_line care?

Therefore, we’re left with 2). There’s almost nothing wrong with this option, since it passes any and all error-related information from lower level functions without any loss. However, using a wrapper type to grant (presumably dynamic) access to any lower-level error type it may be transporting is cumbersome and (like Niall Douglas explains) in general probably requires dynamic allocations. It is better to use independent error types that communicate the additional information not available in the original error object, while error handlers rely on LEAF to provide efficient access to any and all low-level error types, as needed.

Alternatives to LEAF

Below we offer a comparison of LEAF to Boost Exception and to Boost Outcome.

Comparison to Boost Exception

While LEAF can be used without exception handling, in the use case when errors are communicated by throwing exceptions, it can be viewed as a better, more efficient alternative to Boost Exception. LEAF has the following advantages over Boost Exception:

  • LEAF does not allocate memory dynamically;

  • LEAF does not waste system resources communicating error objects not used by specific error handling functions;

  • LEAF does not store the error objects in the exception object, and therefore it is able to augment exceptions thrown by external libraries (Boost Exception can only augment exceptions of types that derive from boost::exception).

The following tables outline the differences between the two libraries which should be considered when code that uses Boost Exception is refactored to use LEAF instead:

Table 2. Defining a custom type for transporting values of type T
Boost Exception LEAF
typedef error_info<struct my_info_,T> my_info;
struct my_info { T value; };
Table 3. Passing arbitrary info at the point of the throw
Boost Exception LEAF
throw my_exception() <<
  my_info(x) <<
  my_info(y);
throw leaf::exception( my_exception(),
  my_info{x},
  my_info{y} );
Table 4. Augmenting exceptions in error-neutral contexts
Boost Exception LEAF
try
{
  f();
}
catch( boost::exception & e )
{
  e << my_info(x);
  throw;
}
auto load = leaf::preload( my_info{x} );

f();
Table 5. Obtaining arbitrary info at the point of the catch
Boost Exception LEAF
try
{
  f();
}
catch( my_exception & e )
{
  if( T * v = get_error_info<my_info>(e) )
  {
    //my_info is available in e.
  }
}
leaf::try_catch(
  []
  {
    f();
  }
  []( leaf::catch_<my_exception>, my_info const & x )
  {
    //my_info is available with
    //the caught exception.
  } );
Table 6. Transporting of E-objects
Boost Exception LEAF

All supplied boost::error_info objects are allocated dynamically and stored in the boost::exception subobject of exception objects.

User-defined error objects are stored statically in the scope of try_catch, but only if their types are needed to handle errors; otherwise they are discarded.

Table 7. Transporting of E-objects across thread boundaries
Boost Exception LEAF

boost::exception_ptr automatically captures boost::error_info objects stored in a boost::exception and can transport them across thread boundaries.

Transporting error objects across thread boundaries requires the use of capture.

Table 8. Printing of error objects in automatically-generated diagnostic information messages
Boost Exception LEAF

boost::error_info types may define conversion to std::string by providing to_string overloads or by overloading operator<< for std::ostream.

LEAF does not use to_string. Error types may define operator<< overloads for std::ostream.

The fact that Boost Exception stores all supplied boost::error_info objects — while LEAF discards them if they aren’t needed — affects the completeness of the message we get when we print leaf::diagnostic_info objects, compared to the string returned by boost::diagnostic_information.

If the user requires a complete diagnostic message, the solution is to use leaf::verbose_diagnostic_info. In this case, before unused error objects are discarded by LEAF, they are converted to string and printed. Note that this allocates memory dynamically.


Comparison to Boost Outcome

Design Differences

Like LEAF, the Boost Outcome library is designed to work in low latency environments. It provides two class templates, result<> and outcome<>:

  • result<T,EC,NVP> can be used as the return type in noexcept functions which may fail, where T specifies the type of the return value in case of success, while EC is an "error code" type. Semantically, result<T,EC> is similar to std::variant<T,EC>. Naturally, EC defaults to std::error_code.

  • outcome<T,EC,EP,NVP> is similar to result<>, but in case of failure, in addition to the "error code" type EC it can hold a "pointer" object of type EP, which defaults to std::exception_ptr.

NVP is a policy type used to customize the behavior of .value() when the result<> or the outcome<> object contains an error.

The idea is to use result<> to communicate failures which can be fully specified by an "error code", and outcome<> to communicate failures that require additional information.

Another way to describe this design is that result<> is used when it suffices to return an error object of some static type EC, while outcome<> can also transport a polymorphic error object, using the pointer type EP.

In the default configuration of outcome<T> the additional information — or the additional polymorphic object — is an exception object held by std::exception_ptr. This targets the use case when an exception thrown by a lower-level library function needs to be transported through some intermediate contexts that are not exception-safe, to a higher-level context able to handle it. LEAF directly supports this use as well, see exception_to_result.

Similar reasoning drives the design of LEAF as well. The difference is that while both libraries recognize the need to transport "something else" in addition to an "error code", LEAF provides an efficient solution to this problem, while Outcome shifts this burden to the user.

The leaf::result<> template deletes both EC and EP, which decouples it from the type of the error objects that are transported in case of a failure. This enables lower-level functions to freely communicate anything and everything they "know" about the failure: error code, even multiple error codes, file names, request IDs, etc. At the same time, the higher-level error-handling functions control which of this information is needed in a specific client program and which is not. This is ideal, because:

  • Authors of lower-level library functions lack context to determine which of the information that is both relevant to the error and naturally available to them needs to be communicated in order for a particular client program to recover from that error;

  • Authors of higher-level error-handling functions can easily and confidently make this determination, which they communicate naturally to LEAF, by simply writing the different error handlers. LEAF automatically and efficiently transports the needed E-objects while discarding the ones handlers don’t use, saving resources.

The LEAF examples include an adaptation of the program from the Boost Outcome result<> tutorial. You can view it on GitHub.
Programs using LEAF for error-handling are not required to use leaf::result<T>; for example, it is possible to use outcome::result<T> with LEAF.

The Interoperability Problem

The Boost Outcome documentation discusses the important problem of bringing together multiple libraries — each using its own error reporting mechanism — and incorporating them in a robust error handling infrastructure in a client program.

Users are advised that whenever possible they should use a common error handling system throughout their entire codebase, but because this is not practical, both the result<> and the outcome<> templates can carry user-defined "payloads".

The following analysis is from the Boost Outcome documentation:

If library A uses result<T, libraryA::failure_info>, and library B uses result<T, libraryB::error_info> and so on, there becomes a problem for the application writer who is bringing in these third party dependencies and tying them together into an application. As a general rule, each third party library author will not have built in explicit interoperation support for unknown other third party libraries. The problem therefore lands with the application writer.

The application writer has one of three choices:

  1. In the application, the form of result used is result<T, std::variant<E1, E2, …​>> where E1, E2 … are the failure types for every third party library in use in the application. This has the advantage of preserving the original information exactly, but comes with a certain amount of use inconvenience and maybe excessive coupling between high level layers and implementation detail.

  2. One can translate/map the third party’s failure type into the application’s failure type at the point of the failure exiting the third party library and entering the application. One might do this, say, with a C preprocessor macro wrapping every invocation of the third party API from the application. This approach may lose the original failure detail, or mis-map under certain circumstances if the mapping between the two systems is not one-one.

  3. One can type erase the third party’s failure type into some application failure type, which can later be reconstituted if necessary. This is the cleanest solution with the least coupling issues and no problems with mis-mapping, but it almost certainly requires the use of malloc which the previous two did not.

The analysis above (emphasis added) is clear and precise, but LEAF and Boost Outcome tackle the interoperability problem differently:

  • The Boost Outcome design asserts that the "cleanest" solution based on type-erasure is suboptimal ("almost certainly requires the use of malloc"), and instead provides a system for injecting custom converters into the outcome::convert namespace, used to translate between library-specific and program-wide error types, even though this approach "may lose the original failure detail".

  • The LEAF design asserts that coupling the signatures of error-neutral functions with the static types of the error objects they need to forward to the caller does not scale, and instead transports error objects directly to error-handling scopes where they are stored statically, effectively implementing the third choice outlined above (without the use of malloc).

Further, consider that Outcome aims to hopefully become the one error-handling API all libraries would use, and in theory everyone would benefit from uniformity and standardization. But the reality is that this is wishful thinking. In fact, that reality is reflected in the design of outcome::result<>, in its failure to commit to using std::error_code for its intended purpose: to become the standard type for transporting error codes. The fact is that std::error_code became yet another error code type programmers need to understand and support.

In contrast, the design of LEAF acknowledges that C++ programmers don’t even agree on what a string is. If your project uses 10 different libraries, this probably means 15 different ways to report errors, sometimes across uncooperative interfaces (e.g. C APIs). LEAF helps you get the job done elegantly and efficiently.

Benchmark

This benchmark compares the performance of LEAF and Boost Outcome.

Distribution

The source code is available on GitHub.

Copyright (c) 2018-2019 Emil Dotchevski. Distributed under the Boost Software License, Version 1.0.

Please post questions and feedback on the Boost Developers Mailing List (LEAF is not part of Boost).

Portability

LEAF requires a C++11 compiler.

See unit test matrix at Travis-CI and AppVeyor.

Building

LEAF is a header-only library and it requires no building. It does not depend on Boost or on any other library.

The unit tests can be run with Boost Build or with Meson Build. To run the unit tests:

  1. If using Boost Build:

    1. Clone LEAF under your boost/libs directory.

    2. Execute:

      cd leaf/test
      ../../../b2
  2. If using Meson Build:

    1. Clone LEAF into any local directory.

    2. Execute:

      cd leaf
      meson bld/debug
      cd bld/debug
      meson test

Configuration Macros

The following configuration macros are recognized:

  • LEAF_DIAGNOSTICS: Defining this macro to 0 stubs out both diagnostic_info and verbose_diagnostic_info, which could improve the performance of the error path in some programs (if the macro is left undefined, LEAF defines it as 1).

  • LEAF_NO_EXCEPTIONS: Disables all exception handling support. If left undefined, LEAF defines it based on the compiler configuration (e.g. -fno-exceptions).

  • LEAF_NO_THREADS: Disable all multi-thread support.

Acknowledgements

Special thanks to Peter Dimov and Sorin Fetche.

Ivo Belchev, Sean Palmer, Jason King, Vinnie Falco, Glen Fernandes, Nir Friedman, Augustín Bergé — thanks for the valuable feedback.

Documentation rendered by Asciidoctor with these customizations.


1. https://herbsutter.com/2007/01/24/questions-about-exception-specifications/