]
endif::[]
Lightweight Error Augmentation Framework written in {CPP}11 | Emil Dotchevski
ifndef::backend-pdf[]
:toc: left
:toclevels: 3
:toc-title:
[.text-right]
https://github.com/boostorg/leaf[GitHub] | https://boostorg.github.io/leaf/leaf.pdf[PDF]
endif::[]
[abstract]
== Abstract
Boost LEAF is a lightweight error handling library for {CPP}11. Features:
====
* Portable single-header format, no dependencies.
* Tiny code size when configured for embedded development.
* No dynamic memory allocations, even with very large payloads.
* Deterministic unbiased efficiency on the "happy" path and the "sad" path.
* Error objects are handled in constant time, independent of call stack depth.
* Can be used with or without exception handling.
====
ifndef::backend-pdf[]
[grid=none, frame=none]
|====
| <> \| <> \| https://github.com/boostorg/leaf/blob/master/doc/whitepaper.md[Whitepaper] \| https://github.com/boostorg/leaf/blob/master/benchmark/benchmark.md[Benchmark] >| Reference: <> \| <> \| <> \| <> \| <>
|====
endif::[]
[[support]]
== Support
* https://Cpplang.slack.com[cpplang on Slack] (use the `#boost` channel)
* https://lists.boost.org/mailman/listinfo.cgi/boost-users[Boost Users Mailing List]
* https://lists.boost.org/mailman/listinfo.cgi/boost[Boost Developers Mailing List]
* https://github.com/boostorg/leaf/issues[Report issues] on GitHub
[[distribution]]
== Distribution
LEAF is distributed under the http://www.boost.org/LICENSE_1_0.txt[Boost Software License, Version 1.0].
There are three distribution channels:
* LEAF is included in official https://www.boost.org/[Boost] releases (starting with Boost 1.75), and therefore available via most package managers.
* The source code is hosted on https://github.com/boostorg/leaf[GitHub].
* For maximum portability, the latest LEAF release is also available in single-header format: simply download link:https://raw.githubusercontent.com/boostorg/leaf/gh-pages/leaf.hpp[leaf.hpp] (direct download link).
NOTE: LEAF does not depend on Boost or other libraries.
[[tutorial]]
== Tutorial
What is a failure? It is simply the inability of a function to return a valid result, instead producing an error object describing the reason for the failure.
A typical design is to return a variant type, e.g. `result`. Internally, such variant types must store a discriminant (in this case a boolean) to indicate whether the object holds a `T` or an `E`.
The design of LEAF is informed by the observation that the immediate caller must have access to the discriminant in order to determine the availability of a valid `T`, but otherwise it rarely needs to access the `E`. The error object is only needed once an error handling scope is reached.
Therefore what would have been a `result` becomes `result`, which stores the discriminant and (optionally) a `T`, while the `E` is communicated directly to the error handling scope where it is needed.
The benefit of this decomposition is that `result` becomes extremely lightweight, as it is not coupled with error types; further, error objects are communicated in constant time (independent of the call stack depth). Even very large objects are handled efficiently without dynamic memory allocation.
=== Reporting Errors
A function that reports an error is pretty straight-forward:
[source,c++]
----
enum class err1 { e1, e2, e3 };
leaf::result f()
{
....
if( error_detected )
return leaf::new_error( err1::e1 ); // Pass an error object of any type
// Produce and return a T.
}
----
[.text-right]
<> | <>
'''
[[checking_for_errors]]
=== Checking for Errors
Checking for errors communicated by a `leaf::result` works as expected:
[source,c++]
----
leaf::result g()
{
leaf::result r = f();
if( !r )
return r.error();
T const & v = r.value();
// Use v to produce a valid U
}
----
[.text-right]
<>
TIP: The the result of `r.error()` is compatible with any instance of the `leaf::result` template. In the example above, note that `g` returns a `leaf::result`, while `r` is of type `leaf::result`.
The boilerplate `if` statement can be avoided using `BOOST_LEAF_AUTO`:
[source,c++]
----
leaf::result g()
{
BOOST_LEAF_AUTO(v, f()); // Bail out on error
// Use v to produce a valid U
}
----
[.text-right]
<>
`BOOST_LEAF_AUTO` can not be used with `void` results; in that case, to avoid the boilerplate `if` statement, use `BOOST_LEAF_CHECK`:
[source,c++]
----
leaf::result f();
leaf::result g()
{
BOOST_LEAF_CHECK(f()); // Bail out on error
return 42;
}
----
[.text-right]
<>
On implementations that define `pass:[__GNUC__]` (e.g. GCC/clang), the `BOOST_LEAF_CHECK` macro definition takes advantage of https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html[GNU C statement expressions]. In this case, in addition to its portable usage with `result`, `BOOST_LEAF_CHECK` can be used in expressions with non-`void` result types:
[source,c++]
----
leaf::result f();
float g(int x);
leaf::result t()
{
return g( BOOST_LEAF_CHECK(f()) );
}
----
The following is the portable alternative:
[source,c++]
----
leaf::result t()
{
BOOST_LEAF_AUTO(x, f());
return g(x);
}
----
'''
[[tutorial-error_handling]]
=== Error Handling
Error handling scopes must use a special syntax to indicate that they need to access error objects. The following excerpt attempts several operations and handles errors of type `err1`:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1, v2);
},
[]( err1 e ) -> leaf::result
{
if( e == err1::e1 )
.... // Handle err1::e1
else
.... // Handle any other err1 value
} );
----
[.text-right]
<> | <> | <>
The first lambda passed to `try_handle_some` is executed first; it attempts to produce a `result`, but it may fail.
The second lambda is an error handler: it will be called iff the first lambda fails and an error object of type `err1` was communicated to LEAF. That object is stored on the stack, local to the `try_handle_some` function (LEAF knows to allocate this storage because we gave it an error handler that takes an `err1`). Error handlers passed to `leaf::try_handle_some` can return a valid `leaf::result` but are allowed to fail.
It is possible for an error handler to specify that it can only deal with some values of a given error type:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1. v2);
},
[]( leaf::match ) -> leaf::result
{
// Handle err::e1 or err1::e3
},
[]( err1 e ) -> leaf::result
{
// Handle any other err1 value
} );
----
[.text-right]
<> | <> | <> | <>
LEAF considers the provided error handlers in order, and calls the first one for which it can supply arguments, based on the error objects currently being communicated. Above:
* The first error handler uses the predicate `leaf::match` to specify that it should only be considered if an error object of type `err1` is available, and its value is either `err1::e1` or `err1::e3`.
* Otherwise the second error handler will be called if an error object of type `err1` is available, regardless of its value.
* Otherwise `leaf::try_handle_some` fails.
It is possible for an error handler to conditionally leave the current failure unhandled:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1. v2);
},
[]( err1 e, leaf::error_info const & ei ) -> leaf::result
{
if( <> )
return valid_U;
else
return ei.error();
} );
----
[.text-right]
<> | <> | <> | <>
Any error handler can take an argument of type `leaf::error_info const &` to get access to generic information about the error being handled; in this case we use the `error` member function, which returns the unique <> of the current error; we use it to initialize the returned `leaf::result`, effectively propagating the current error out of `try_handle_some`.
TIP: If we wanted to signal a new error (rather than propagating the current error), in the `return` statement we would invoke the `leaf::new_error` function.
If we want to ensure that all possible failures are handled, we use `leaf::try_handle_all` instead of `leaf::try_handle_some`:
[source,c++]
----
U r = leaf::try_handle_all(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1. v2);
},
[]( leaf::match ) -> U
{
// Handle err::e1
},
[]( err1 e ) -> U
{
// Handle any other err1 value
},
[]() -> U
{
// Handle any other failure
} );
----
[.text-right]
<>
The `leaf::try_handle_all` function enforces at compile time that at least one of the supplied error handlers takes no arguments (and therefore is able to handle any failure). In addition, all error handlers are forced to return a valid `U`, rather than a `leaf::result`, so that `leaf::try_handle_all` is guaranteed to succeed, always.
'''
=== Working with Different Error Types
It is of course possible to provide different handlers for different error types:
[source,c++]
----
enum class err1 { e1, e2, e3 };
enum class err2 { e1, e2 };
....
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1, v2);
},
[]( err1 e ) -> leaf::result
{
// Handle errors of type `err1`.
},
[]( err2 e ) -> leaf::result
{
// Handle errors of type `err2`.
} );
----
[.text-right]
<> | <> | <>
Recall that error handlers are always considered in order:
* The first error handler will be used if an error object of type `err1` is available;
* otherwise, the second error handler will be used if an error object of type `err2` is available;
* otherwise, `leaf::try_handle_some` fails.
'''
=== Working with Multiple Error Objects
The `leaf::new_error` function can be invoked with multiple error objects, for example to communicate an error code and the relevant file name:
[source,c++]
----
enum class io_error { open_error, read_error, write_error };
struct e_file_name { std::string value; }
leaf::result open_file( char const * name )
{
....
if( open_failed )
return leaf::new_error(io_error::open_error, e_file_name {name});
....
}
----
[.text-right]
<> | <>
Similarly, error handlers may take multiple error objects as arguments:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(f, open_file(fn));
....
},
[]( io_error ec, e_file_name fn ) -> leaf::result
{
// Handle I/O errors when a file name is available.
},
[]( io_error ec ) -> leaf::result
{
// Handle I/O errors when no file name is available.
} );
----
[.text-right]
<> | <> | <>
Once again, error handlers are considered in order:
* The first error handler will be used if an error object of type `io_error` _and_ and error_object of type `e_file_name` are available;
* otherwise, the second error handler will be used if an error object of type `io_error` is avaliable;
* otherwise, `leaf_try_handle_some` fails.
An alternative way to write the above is to provide a single error handler that takes the `e_file_name` argument as a pointer:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(f, open_file(fn));
....
},
[]( io_error ec, e_file_name const * fn ) -> leaf::result
{
if( fn )
.... // Handle I/O errors when a file name is available.
else
.... // Handle I/O errors when no file name is available.
} );
----
[.text-right]
<> | <> | <>
An error handler is never dropped for lack of error objects of types which the handler takes as pointers; in this case LEAF simply passes `0` for these arguments.
TIP: Error handlers can take arguments by value, by (`const`) reference or as a (`const`) pointer. It the latter case, changes to the error object state will be propagated up the call stack if the failure is not handled.
[[tutorial-augmenting_errors]]
=== Augmenting Errors
Let's say we have a function `parse_line` which could fail due to an `io_error` or a `parse_error`:
[source,c++]
----
enum class io_error { open_error, read_error, write_error };
enum class parse_error { bad_syntax, bad_range };
leaf::result parse_line( FILE * f );
----
The `leaf::on_error` function can be used to automatically associate additional error objects with any failure that is "in flight":
[source,c++]
----
struct e_line { int value; };
leaf::result process_file( FILE * f )
{
for( int current_line = 1; current_line != 10; ++current_line )
{
auto load = leaf::on_error( e_line {current_line} );
BOOST_LEAF_AUTO(v, parse_line(f));
// use v
}
}
----
[.text-right]
<> | <>
Because `process_file` does not handle errors, it remains neutral to failures, except to attach the `current_line` if something goes wrong. The object returned by `on_error` holds a copy of the `current_line` wrapped in `struct e_line`. If `parse_line` succeeds, the `e_line` object is simply discarded; but if it fails, the `e_line` object will be automatically "attached" to the failure.
Such failures can then be handled like so:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[&]() -> leaf::result
{
BOOST_LEAF_CHECK( process_file(f) );
},
[]( parse_error e, e_line current_line )
{
std::cerr << "Parse error at line " << current_line.value << std::endl;
},
[]( io_error e, e_line current_line )
{
std::cerr << "I/O error at line " << current_line.value << std::endl;
},
[]( io_error e )
{
std::cerr << "I/O error" << std::endl;
} );
----
[.text-right]
<> | <>
The following is equivalent, and perhaps simpler:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_CHECK( process_file(f) );
},
[]( parse_error e, e_line current_line )
{
std::cerr << "Parse error at line " << current_line.value << std::endl;
},
[]( io_error e, e_line const * current_line )
{
std::cerr << "Parse error";
if( current_line )
std::cerr << " at line " << current_line->value;
std::cerr << std::endl;
} );
----
'''
[[tutorial-exception_handling]]
=== Exception Handling
What happens if an operation throws an exception? Not to worry, both `try_handle_some` and `try_handle_all` catch exceptions and are able to pass them to any compatible error handler:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_CHECK( process_file(f) );
},
[]( std::bad_alloc const & )
{
std::cerr << "Out of memory!" << std::endl;
},
[]( parse_error e, e_line l )
{
std::cerr << "Parse error at line " << l.value << std::endl;
},
[]( io_error e, e_line const * l )
{
std::cerr << "Parse error";
if( l )
std::cerr << " at line " << l.value;
std::cerr << std::endl;
} );
----
[.text-right]
<> | <> | <>
Above, we have simply added an error handler that takes a `std::bad_alloc`, and everything "just works" as expected: LEAF will dispatch error handlers correctly no matter if failures are communicated via `leaf::result` or by an exception.
Of course, if we use exception handling exclusively, we do not need `leaf::result` at all. In this case we use `leaf::try_catch`:
[source,c++]
----
leaf::try_catch(
[]
{
process_file(f);
},
[]( std::bad_alloc const & )
{
std::cerr << "Out of memory!" << std::endl;
},
[]( parse_error e, e_line l )
{
std::cerr << "Parse error at line " << l.value << std::endl;
},
[]( io_error e, e_line const * l )
{
std::cerr << "Parse error";
if( l )
std::cerr << " at line " << l.value;
std::cerr << std::endl;
} );
----
[.text-right]
<>
Remarkably, we did not have to change the error handlers! But how does this work? What kind of exceptions does `process_file` throw?
LEAF enables a novel technique of exception handling, which does not use an exception type hierarchy to classify failures and does not carry data in exception objects. Recall that when failures are communicated via `leaf::result`, we call `leaf::new_error` in a `return` statement, passing any number of error objects which are sent directly to the correct error handling scope:
[source,c++]
----
enum class err1 { e1, e2, e3 };
enum class err2 { e1, e2 };
....
leaf::result f()
{
....
if( error_detected )
return leaf::new_error(err1::e1, err2::e2);
// Produce and return a T.
}
----
[.text-right]
<> | <>
When using exception handling this becomes:
[source,c++]
----
enum class err1 { e1, e2, e3 };
enum class err2 { e1, e2 };
T f()
{
if( error_detected )
leaf::throw_exception(err1::e1, err2::e2);
// Produce and return a T.
}
----
[.text-right]
<>
The `leaf::throw_exception` function handles the passed error objects just like `leaf::new_error` does, and then throws an object of a type that derives from `std::exception`. Using this technique, the exception type is not important: `leaf::try_catch` catches all exceptions, then goes through the usual LEAF error handler selection procedure.
If instead we want to use the legacy convention of throwing different types to indicate different failures, we simply pass an exception object (that is, an object of a type that derives from `std::exception`) as the first argument to `leaf::throw_exception`:
[source,c++]
----
leaf::throw_exception(std::runtime_error("Error!"), err1::e1, err2::e2);
----
In this case the returned object will be of type that derives from `std::runtime_error`, rather than from `std::exception`.
Finally, `leaf::on_error` "just works" as well. Here is our `process_file` function rewritten to work with exceptions, rather than return a `leaf::result` (see <>):
[source,c++]
----
int parse_line( FILE * f ); // Throws
struct e_line { int value; };
void process_file( FILE * f )
{
for( int current_line = 1; current_line != 10; ++current_line )
{
auto load = leaf::on_error( e_line {current_line} );
int v = parse_line(f);
// use v
}
}
----
[.text-right]
<>
'''
=== Using External `result` Types
Static type checking creates difficulties in error handling interoperability in any non-trivial project. Using exception handling alleviates this problem somewhat because in that case error types are not burned into function signatures, so errors easily punch through multiple layers of APIs; but this doesn't help {CPP} in general because the community is fractured on the issue of exception handling. That debate notwithstanding, the reality is that {CPP} programs need to handle errors communicated through multiple layers of APIs via a plethora of error codes, `result` types and exceptions.
LEAF enables application developers to shake error objects out of each individual library's `result` type and send them to error handling scopes verbatim. Here is an example:
[source,c++]
----
lib1::result foo();
lib2::result bar();
int g( int a, int b );
leaf::result f()
{
auto a = foo();
if( !a )
return leaf::new_error( a.error() );
auto b = bar();
if( !b )
return leaf::new_error( b.error() );
return g( a.value(), b.value() );
}
----
[.text-right]
<> | <>
Later we simply call `leaf::try_handle_some` passing an error handler for each type:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
return f();
},
[]( lib1::error_code ec ) -> leaf::result
{
// Handle lib1::error_code
},
[]( lib2::error_code ec ) -> leaf::result
{
// Handle lib2::error_code
} );
}
----
[.text-right]
<> | <>
A possible complication is that we might not have the option to return `leaf::result` from `f`: a third party API may impose a specific signature on it, forcing it to return a library-specific `result` type. This would be the case when `f` is intended to be used as a callback:
[source,c++]
----
void register_callback( std::function()> const & callback );
----
Can we use LEAF in this case? Actually we can, as long as `lib3::result` is able to communicate a `std::error_code`. We just have to let LEAF know, by specializing the `is_result_type` template:
[source,c++]
----
namespace boost { namespace leaf {
template
struct is_result_type>: std::true_type;
} }
----
[.text-right]
<>
With this in place, `f` works as before, even though `lib3::result` isn't capable of transporting `lib1` errors or `lib2` errors:
[source,c++]
----
lib1::result foo();
lib2::result bar();
int g( int a, int b );
lib3::result f()
{
auto a = foo();
if( !a )
return leaf::new_error( a.error() );
auto b = bar();
if( !b )
return leaf::new_error( b.error() );
return g( a.value(), b.value() );
}
----
[.text-right]
<>
The object returned by `leaf::new_error` converts implicitly to `std::error_code`, using a LEAF-specific `error_category`, which makes `lib3::result` compatible with `leaf::try_handle_some` (and with `leaf::try_handle_all`):
[source,c++]
----
lib3::result r = leaf::try_handle_some(
[]() -> lib3::result
{
return f();
},
[]( lib1::error_code ec ) -> lib3::result
{
// Handle lib1::error_code
},
[]( lib2::error_code ec ) -> lib3::result
{
// Handle lib2::error_code
} );
}
----
[.text-right]
<>
'''
[[tutorial-model]]
=== Error Communication Model
==== `noexcept` API
The following figure illustrates how error objects are transported when using LEAF without exception handling:
.LEAF noexcept Error Communication Model
image::LEAF-1.png[]
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 `on_error` in `f3`: it caches the passed error 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 error 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` 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 error objects associated with the `error_id` it received from `f2`, and processes a list of user-provided error handlers, in order, until it finds a handler with arguments that can be supplied using the available (in `ctx`) error objects. That handler is called to deal with the failure.
==== Exception Handling API
The following figure illustrates the slightly different error communication model used when errors are reported by throwing exceptions:
.LEAF Error Communication Model Using Exception Handling
image::LEAF-2.png[]
The main difference is that the call to `new_error` is implicit in the call to the function template `leaf::throw_exception`, which in this case takes an exception object of type `Ex`, and throws an exception object of unspecified type that derives publicly from `Ex`.
[[tutorial-interoperability]]
==== Interoperability
Ideally, when an error is detected, a program using LEAF would always call <>, ensuring that each encountered failure is definitely assigned a unique <>, which then is reliably delivered, by an exception or by a `result` 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 is able to transport a `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 <>, which returns the error ID returned by the most recent call (from this thread) to <>. One possible approach to solving the problem is to use the following logic (implemented by the <> type):
. Before calling the uncooperative API, call <> and cache the returned value.
. Call the API, then call `current_error` again:
.. If this returns the same value as before, pass the error objects to `new_error` to associate them with a new `error_id`;
.. 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.
For a detailed tutorial see <>.
TIP: To avoid ambiguities, whenever possible, use the <> function template to throw exceptions, to ensure that the exception object transports a unique `error_id`; better yet, use the <> macro, which in addition will capture `pass:[__FILE__]` and `pass:[__LINE__]`.
'''
[[tutorial-loading]]
=== Loading of Error Objects
To load an error object is to move it into an active <>, usually local to a <>, a <> or a <> scope in the calling thread, where it becomes uniquely associated with a specific <> -- or discarded if storage is not available.
Various LEAF functions take a list of error 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 <>:
[source,c++]
----
return leaf::new_error(ec, e_input_name{n1}, e_output_name{n2});
----
Alternatively, error objects may be loaded using a `result` that is already communicating an error. This way they become associated with that error, rather than with a new error:
[source,c++]
----
leaf::result f() noexcept;
leaf::result g( char const * fn ) noexcept
{
if( leaf::result r = f() )
{ <1>
....;
return { };
}
else
{
return r.load( e_file_name{fn} ); <2>
}
}
----
[.text-right]
<> | <>
<1> Success! Use `r.value()`.
<2> `f()` has failed; here we associate an additional `e_file_name` with the error. However, this association occurs iff in the call stack leading to `g` there are error handlers that take an `e_file_name` argument. Otherwise, the object passed to `load` is discarded. In other words, the passed objects are loaded iff the program actually uses them to handle errors.
Besides error objects, `load` can take function arguments:
* If we pass a function that takes no arguments, it is invoked, and the returned error object is loaded.
+
Consider that if we pass to `load` an error object that is not needed by any error handler, it will be discarded. If the object is expensive to compute, it would be better if the computation can be skipped as well. Passing a function with no arguments to `load` is an excellent way to achieve this behavior:
+
[source,c++]
----
struct info { .... };
info compute_info() noexcept;
leaf::result operation( char const * file_name ) noexcept
{
if( leaf::result r = try_something() )
{ <1>
....
return { };
}
else
{
return r.load( <2>
[&]
{
return compute_info();
} );
}
}
----
[.text-right]
<> | <>
+
<1> Success! Use `r.value()`.
<2> `try_something` has failed; `compute_info` will only be called if an error handler exists which takes a `info` argument.
+
* If we pass a function that takes a single argument of type `E &`, LEAF calls the function with the object of type `E` currently loaded in an active `context`, associated with the error. If no such 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:
+
[source,c++]
----
struct e_relevant_file_names
{
std::vector value;
};
leaf::result operation( char const * file_name ) noexcept
{
if( leaf::result r = try_something() )
{ <1>
....
return { };
}
else
{
return r.load( <2>
[&](e_relevant_file_names & e)
{
e.value.push_back(file_name);
} );
}
}
----
[.text-right]
<> | <>
+
<1> Success! Use `r.value()`.
<2> `try_something` has failed -- add `file_name` to the `e_relevant_file_names` object, associated with the `error_id` communicated in `r`. Note, however, that the passed function will only be called iff in the call stack there are error handlers that take an `e_relevant_file_names` object.
'''
[[tutorial-on_error]]
=== Using `on_error`
It is not typical for an error reporting function to be able to supply all of the data needed by a suitable error handling function in order to recover from the failure. For example, a function that reports `FILE` failures 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. Below, while `parse_info` can't report the file name, `parse_file` can and does:
[source,c++]
----
leaf::result parse_info( FILE * f ) noexcept; <1>
leaf::result parse_file( char const * file_name ) noexcept
{
auto load = leaf::on_error(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 );
}
----
[.text-right]
<> | <> | <>
<1> `parse_info` parses `f`, communicating errors using `result`.
<2> Using `on_error` 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.
TIP: `on_error` -- like `load` -- can be passed any number of arguments.
When we invoke `on_error`, we can pass three kinds of arguments:
. Actual error objects (like in the example above);
. Functions that take no arguments and return an error object;
. Functions that take an error object by mutable reference.
If we want to use `on_error` to capture `errno`, we can't just pass <> to it, because at that time it hasn't been set (yet). Instead, we'd pass a function that returns it:
[source,c++]
----
void read_file(FILE * f) {
auto load = leaf::on_error([]{ return e_errno{errno}; });
....
size_t nr1=fread(buf1,1,count1,f);
if( ferror(f) )
leaf::throw_exception();
size_t nr2=fread(buf2,1,count2,f);
if( ferror(f) )
leaf::throw_exception();
size_t nr3=fread(buf3,1,count3,f);
if( ferror(f) )
leaf::throw_exception();
....
}
----
Above, if `throw_exception` is called, LEAF will invoke the function passed to `on_error` and associate the returned `e_errno` object with the exception.
The final argument type that can be passed to `on_error` is a function that takes a single mutable error object reference. In this case, `on_error` uses it similarly to how such functions are used by `load`; see <>.
'''
[[tutorial-predicates]]
=== Using Predicates to Handle Errors
Usually, LEAF error handlers are selected based on the type of the arguments they take and the type of the available error objects. When an error handler takes a predicate type as an argument, the <> is able to also take into account the _value_ of the available error objects.
Consider this error code enum:
[source,c++]
----
enum class my_error
{
e1=1,
e2,
e3
};
----
We could handle `my_error` errors like so:
[source,c++]
----
return leaf::try_handle_some(
[]
{
return f(); // returns leaf::result
},
[]( my_error e )
{ <1>
switch(e)
{
case my_error::e1:
....; <2>
break;
case my_error::e2:
case my_error::e3:
....; <3>
break;
default:
....; <4>
break;
} );
----
<1> This handler will be selected if we've got a `my_error` object.
<2> Handle `e1` errors.
<3> Handle `e2` and `e3` errors.
<4> Handle bad `my_error` values.
If `my_error` object is available, LEAF will call our error handler. If not, the failure will be forwarded to our caller.
This can be rewritten using the <> predicate to organize the different cases in different error handlers. The following is equivalent:
[source,c++]
----
return leaf::try_handle_some(
[]
{
return f(); // returns leaf::result
},
[]( leaf::match m )
{ <1>
assert(m.matched == my_error::e1);
....;
},
[]( leaf::match m )
{ <2>
assert(m.matched == my_error::e2 || m.matched == my_error::e3);
....;
},
[]( my_error e )
{ <3>
....;
} );
----
<1> We've got a `my_error` object that compares equal to `e1`.
<2> We`ve got a `my_error` object that compares equal to either `e2` or `e3`.
<3> Handle bad `my_error` values.
The first argument to the `match` template generally specifies the type `E` of the error object `e` that must be available for the error handler to be considered at all. Typically, the rest of the arguments are values. The error handler is dropped if `e` does not compare equal to any of them.
In particular, `match` works great with `std::error_code`. The following handler is designed to handle `ENOENT` errors:
[source,c++]
----
[]( leaf::match )
{
}
----
This, however, requires {CPP}17 or newer, because it is impossible to infer the type of the error enum (in this case, `std::errc`) from the specified type `std::error_code`, and {CPP}11 does not allow `auto` template arguments. LEAF provides the following workaround, compatible with {CPP}11:
[source,c++]
----
[]( leaf::match, std::errc::no_such_file_or_directory> )
{
}
----
In addition, it is possible to select a handler based on `std::error_category`. The following handler will match any `std::error_code` of the `std::generic_category` (requires {CPP}17 or newer):
[source,c++]
----
[]( std::error_code, leaf::category> )
{
}
----
TIP: See <> for more examples.
The following predicates are available:
* <>: as described above.
* <>: where `match` compares the object `e` of type `E` with the values `V...`, `match_value` compare `e.value` with the values `V...`.
* <>: similar to `match_value`, but takes a pointer to the data member to compare; that is, `match_member<&E::value, V...>` is equvialent to `match_value`. Note, however, that `match_member` requires {CPP}17 or newer, while `match_value` does not.
* `<>`: Similar to `match`, but checks whether the caught `std::exception` object can be `dynamic_cast` to any of the `Ex` types.
* <> is a special predicate that takes any other predicate `Pred` and requires that an error object of type `E` is available and that `Pred` evaluates to `false`. For example, `if_not>` requires that an object `e` of type `E` is available, and that it does not compare equal to any of the specified `V...`.
Finally, the predicate system is easily extensible, see <>.
NOTE: See also <>.
'''
[[tutorial-binding_handlers]]
=== Binding Error Handlers in a `std::tuple`
Consider this snippet:
[source,c++]
----
leaf::try_handle_all(
[&]
{
return f(); // returns leaf::result
},
[](my_error_enum x)
{
...
},
[](read_file_error_enum y, e_file_name const & fn)
{
...
},
[]
{
...
});
----
[.text-right]
<> | <>
Looks pretty simple, 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 function passed as `TryBlock` for `try_handle_all`:
[source,c++]
----
leaf::try_handle_all(
[&]
{
return g(); // returns leaf::result
},
[](my_error_enum x)
{
...
},
[](read_file_error_enum y, e_file_name const & fn)
{
...
},
[]
{
...
});
----
That works, but it is better to bind our error handlers in a `std::tuple`:
[source,c++]
----
auto error_handlers = std::make_tuple(
[](my_error_enum x)
{
...
},
[](read_file_error_enum y, e_file_name const & fn)
{
...
},
[]
{
...
});
----
The `error_handlers` tuple can later be used with any error handling function:
[source,c++]
----
leaf::try_handle_all(
[&]
{
// Operations which may fail <1>
},
error_handlers );
leaf::try_handle_all(
[&]
{
// Different operations which may fail <2>
},
error_handlers ); <3>
----
[.text-right]
<> | <>
<1> One set of operations which may fail...
<2> A different set of operations which may fail...
<3> ... both using the same `error_handlers`.
Error handling functions accept a `std::tuple` of error handlers in place of any error handler. The behavior is as if the tuple is unwrapped in-place.
'''
[[tutorial-async]]
=== Transporting Error Objects Between Threads
Error objects are stored on the stack in an instance of the <> class template in the scope of e.g. <>, <> or <> functions. When using concurrency, we need a mechanism to collect error objects in one thread, then use them to handle errors in another thread.
LEAF offers two interfaces for this purpose, one using `result`, and another designed for programs that use exception handling.
[[tutorial-async_result]]
==== Using `result`
Let's assume we have a `task` that we want to launch asynchronously, which produces a `task_result` but could also fail:
[source,c++]
----
leaf::result task();
----
Because the task will run asynchronously, in case of a failure we need it to capture the relevant error objects but not handle errors. To this end, in the main thread we bind our error handlers in a `std::tuple`, which we will later use to handle errors from each completed asynchronous task (see <>):
[source,c++]
----
auto error_handlers = std::make_tuple(
[](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 <> object to collect the error 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, we just need to show it our `error_handlers`:
[source,c++]
----
std::shared_ptr ctx = leaf::make_shared_context(error_handlers);
----
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. In this case what we're holding in `ctx` is a `context`, where `E1`, `E2` and `E3` were deduced automatically from the `error_handlers` tuple we passed to `make_shared_context`.
We're now ready to launch our asynchronous task:
[source,c++]
----
std::future> launch_task() noexcept
{
return std::async(
std::launch::async,
[&]
{
std::shared_ptr ctx = leaf::make_shared_context(error_handlers);
return leaf::capture(ctx, &task);
} );
}
----
[.text-right]
<> | <> | <>
That's it! Later when we `get` the `std::future`, we can process the returned `result` in a call to <>, using the `error_handlers` tuple we created earlier:
[source,c++]
----
//std::future> fut;
fut.wait();
return leaf::try_handle_some(
[&]() -> leaf::result
{
BOOST_LEAF_AUTO(r, fut.get());
//Success!
return { }
},
error_handlers );
----
[.text-right]
<> | <> | <>
The reason this works is that in case the `leaf::result` communicates a failure, it is able to hold a `shared_ptr` object. That is why earlier instead of calling `task()` directly, we called `leaf::capture`: it calls the passed function and, in case that fails, it stores the `shared_ptr` we created in the returned `result`, which now doesn't just communicate the fact that an error has occurred, but also holds the `context` object that `try_handle_some` needs in order to supply a suitable handler with arguments.
NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/capture_in_result.cpp?ts=4[capture_in_result.cpp].
[[tutorial-async_eh]]
==== Using Exception Handling
Let's assume we have an asynchronous `task` which produces a `task_result` but could also throw:
[source,c++]
----
task_result task();
----
Just like we saw in <>, first we will bind our error handlers in a `std::tuple`:
[source,c++]
----
auto handle_errors = std::make_tuple(
[](E1 e1, E2 e2)
{
//Deal with E1, E2
....
return { };
},
[](E3 e3)
{
//Deal with E3
....
return { };
} );
----
Launching the task looks the same as before, except that we don't use `result`:
[source,c++]
----
std::future launch_task()
{
return std::async(
std::launch::async,
[&]
{
std::shared_ptr ctx = leaf::make_shared_context(&handle_error);
return leaf::capture(ctx, &task);
} );
}
----
[.text-right]
<> | <>
That's it! Later when we `get` the `std::future`, we can process the returned `task_result` in a call to <>, using the `error_handlers` we saved earlier, as if it was generated locally:
[source,c++]
----
//std::future fut;
fut.wait();
return leaf::try_catch(
[&]
{
task_result r = fut.get(); // Throws on error
//Success!
},
error_handlers );
----
[.text-right]
<>
This works similarly to using `result`, except that the `std::shared_ptr` is transported in an exception object (of unspecified type which <> recognizes and then automatically unwraps the original exception).
NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/capture_in_exception.cpp?ts=4[capture_in_exception.cpp].
'''
[[tutorial-classification]]
=== Classification of Failures
It is common for an interface to define an `enum` that lists all possible error codes that the API reports. The benefit of this approach is that the list is complete and usually well documented:
[source,c++]
----
enum error_code
{
....
read_error,
size_error,
eof_error,
....
};
----
The disadvantage of such flat enums is that they do not support handling of a whole class of failures. Consider the following LEAF error handler:
[source,c++]
----
....
[](leaf::match, leaf::e_file_name const & fn)
{
std::cerr << "Failed to access " << fn.value << std::endl;
},
....
----
[.text-right]
<> | <>
It will get called if the value of the `error_code` enum communicated with the failure is one of `size_error`, `read_error` or `eof_error`. In short, the idea is to handle any input error.
But what if later we add support for detecting and reporting a new type of input error, e.g. `permissions_error`? It is easy to add that to our `error_code` enum; but now our input error handler won't recognize this new input error -- and we have a bug.
If we can use exceptions, the situation is better because exception types can be organized in a hierarchy in order to classify failures:
[source,c++]
----
struct input_error: std::exception { };
struct read_error: input_error { };
struct size_error: input_error { };
struct eof_error: input_error { };
----
In terms of LEAF, our input error exception handler now looks like this:
[source,c++]
----
[](input_error &, leaf::e_file_name const & fn)
{
std::cerr << "Failed to access " << fn.value << std::endl;
},
----
This is future-proof, but still not ideal, because it is not possible to refine the classification of the failure after the exception object has been thrown.
LEAF supports a novel style of error handling where the classification of failures does not use error code values or exception type hierarchies. Instead of our `error_code` enum, we could define:
[source,c++]
----
....
struct input_error { };
struct read_error { };
struct size_error { };
struct eof_error { };
....
----
With this in place, we could define a function `file_read`:
[source,c++]
----
leaf::result file_read( FILE & f, void * buf, int size )
{
int n = fread(buf, 1, size, &f);
if( ferror(&f) )
return leaf::new_error(input_error{}, read_error{}, leaf::e_errno{errno}); <1>
if( n!=size )
return leaf::new_error(input_error{}, eof_error{}); <2>
return { };
}
----
[.text-right]
<> | <> | <>
<1> This error is classified as `input_error` and `read_error`.
<2> This error is classified as `input_error` and `eof_error`.
Or, even better:
[source,c++]
----
leaf::result file_read( FILE & f, void * buf, int size )
{
auto load = leaf::on_error(input_error{}); <1>
int n = fread(buf, 1, size, &f);
if( ferror(&f) )
return leaf::new_error(read_error{}, leaf::e_errno{errno}); <2>
if( n!=size )
return leaf::new_error(eof_error{}); <3>
return { };
}
----
[.text-right]
<> | <> | <> | <>
<1> Any error escaping this scope will be classified as `input_error`
<2> In addition, this error is classified as `read_error`.
<3> In addition, this error is classified as `eof_error`.
This technique works just as well if we choose to use exception handling, we just call `leaf::throw_exception` instead of `leaf::new_error`:
[source,c++]
----
void file_read( FILE & f, void * buf, int size )
{
auto load = leaf::on_error(input_error{});
int n = fread(buf, 1, size, &f);
if( ferror(&f) )
leaf::throw_exception(read_error{}, leaf::e_errno{errno});
if( n!=size )
leaf::throw_exception(eof_error{});
}
----
[.text-right]
<> | <> | <>
NOTE: If the type of the first argument passed to `leaf::throw_exception` derives from `std::exception`, it will be used to initialize the thrown exception object. Here this is not the case, so the function returns a default-initialized `std::exception` object, while the first (and any other) argument is associated with the failure.
Now we can write a future-proof handler for any `input_error`:
[source,c++]
----
....
[](input_error, leaf::e_file_name const & fn)
{
std::cerr << "Failed to access " << fn.value << std::endl;
},
....
----
Remarkably, because the classification of the failure does not depend on error codes or on exception types, this error handler can be used with `try_catch` if we use exception handling, or with `try_handle_some`/`try_handle_all` if we do not.
'''
[[tutorial-exception_to_result]]
=== Converting Exceptions to `result`
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.
TIP: Error handlers that take arguments of types that derive from `std::exception` work correctly -- regardless of whether the error object itself is thrown as an exception, or <> into a <>. The technique described here is only needed when the exception must be communicated through functions which are not exception-safe, or are compiled with exception handling disabled.
Suppose we have an exception type hierarchy and a function `compute_answer_throws`:
[source,c++]
----
class error_base: public std::exception { };
class error_a: public error_base { };
class error_b: public error_base { };
class error_c: public 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` for error handling:
[source,c++]
----
leaf::result