]
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://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: 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 is rare that it needs to access any error objects. They are 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 error objects are delivered directly to the error handling scope where they are 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:
[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]
<> | <> | <>
First, `try_handle_some` executes the first function passed to it; 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 with an error object of type `err1`. 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 declare that it can only handle some specific 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 err1::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 is able to supply arguments, based on the error objects currently being communicated. Above:
* The first error handler will be called iff 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 iff an error object of type `err1` is available, regardless of its value.
* Otherwise `leaf::try_handle_some` is unable to handle the error.
It is possible for an error handler to conditionally leave the 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]
<> | <> | <>
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 also 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 also 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 `nullptr` for these arguments.
TIP: When an error handler takes arguments by mutable reference or pointer, changes to their state are preserved when the error is communicated to the caller.
[[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 `current_line` wrapped in `struct e_line`. If `parse_line` succeeds, the `e_line` object is simply discarded; 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? 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]
<>
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 exception handling technique, which does not require 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 routine.
If instead we want to use the usual 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 thrown exception 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() // Note: return type is not leaf::result
{
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-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 can 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 <>.
'''
[[tutorial-loading]]
=== Loading of Error Objects
Recall that error objects communicated to LEAF are stored on the stack, local to the `try_handle_same`, `try_handle_all` or `try_catch` function used to handle errors. To _load_ an error object means to move it into such storage, if 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 used by an error handler, it will be discarded. If the object is expensive to compute, it would be better if the computation is only performed in case of an error. 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 in the call stack which takes a `info` argument.
+
* If we pass a function that takes a single argument of some 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.
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` communicates errors using `leaf::result`.
<2> `on_error` ensures that the file name is included with any error reported out of `parse_file`. When the `load` object expires, if an error is being reported, the passed `e_file_name` value will be automatically associated with it.
TIP: `on_error` -- like `new_error` -- 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 a single error object by mutable reference.
For example, 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 leaf::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 an exception is thrown, LEAF will invoke the function passed to `on_error` and associate the returned `e_errno` object with the exception.
Finally, if `on_error` is passed a function that takes a single error object by mutable reference, the behavior is similar to how such functions are handled by `load`; see <>.
'''
[[tutorial-predicates]]
=== Using Predicates to Handle Errors
Usually, the compatibility between error handlers and the available error objects is determined based on the type of the arguments they take. 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 ) // handle my_error objects
{
switch(e)
{
case my_error::e1:
....; // Handle e1 error values
break;
case my_error::e2:
case my_error::e3:
....; // Handle e2 and e3 error values
break;
default:
....; // Handle bad my_error values
break;
} );
----
If a `my_error` object is available, LEAF will call our error handler. If not, the failure will be forwarded to the 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 )
{
assert(m.matched == my_error::e1);
....;
},
[]( leaf::match m )
{
assert(m.matched == my_error::e2 || m.matched == my_error::e3);
....;
},
[]( my_error e )
{
....;
} );
----
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. LEAF provides the following workaround, compatible with {CPP}11:
[source,c++]
----
[]( leaf::match, std::errc::no_such_file_or_directory> )
{
}
----
It is also 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...`.
The predicate system is easily extensible, see <>.
NOTE: See also <>.
'''
[[tutorial-binding_handlers]]
=== Reusing Common Error Handlers
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]
<> | <>
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 the `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 also possible to bind the 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 Errors Between Threads
Like exceptions, LEAF error objects are local to a thread. When using concurrency, sometimes we need to collect error objects in one thread, then use them to handle errors in another thread.
LEAF supports this functionality with or without exception handling. In both cases error objects are captured and transported in a `leaf::<>` object.
[[tutorial-async_result]]
==== Transporting Errors Between Threads Without Exception Handling
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 to capture any produced error objects but not handle errors. We do this by invoking `try_capture_all`:
[source,c++]
----
std::future> launch_task() noexcept
{
return std::async(
std::launch::async,
[&]
{
return leaf::try_capture_all(task);
} );
}
----
[.text-right]
<> | <>
In case of a failure, the returned from `try_capture_all` `result` object holds all error objects communicated out of the `task`, at the cost of dynamic allocations. The `result` object can then be stashed away or moved to another thread, and later passed to an error-handling function to unload its content and handle errors:
[source,c++]
----
//std::future> fut;
fut.wait();
return leaf::try_handle_some(
[&]() -> leaf::result
{
BOOST_LEAF_AUTO(r, fut.get());
//Success!
return { }
},
[](E1 e1, E2 e2)
{
//Deal with E1, E2
....
return { };
},
[](E3 e3)
{
//Deal with E3
....
return { };
} );
----
[.text-right]
<> | <> | <>
NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/try_capture_all_result.cpp?ts=4[try_capture_all_result.cpp].
[[tutorial-async_eh]]
==== Transporting Errors Between Threads With Exception Handling
Let's assume we have an asynchronous `task` which produces a `task_result` but could also throw:
[source,c++]
----
task_result task();
----
We use `try_capture_all` to capture all error objects and the `std::current_exception()` in a `result`:
[source,c++]
----
std::future> launch_task()
{
return std::async(
std::launch::async,
[&]
{
return leaf::try_capture_all(task);
} );
}
----
[.text-right]
<>
To handle errors after waiting on the future, we use `try_catch` as usual:
[source,c++]
----
//std::future> fut;
fut.wait();
return leaf::try_catch(
[&]
{
leaf::result r = fut.get();
task_result v = r.value(); // throws on error
//Success!
},
[](E1 e1, E2 e2)
{
//Deal with E1, E2
....
},
[](E3 e3)
{
//Deal with E3
....
} );
----
[.text-right]
<> | <>
NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/try_capture_all_eh.cpp?ts=4[try_capture_all_eh.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.
Using exceptions is an improvement 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 throws 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 compute_answer() noexcept
{
return leaf::exception_to_result(
[]
{
return compute_answer_throws();
} );
}
----
[.text-right]
<> | <>
The `exception_to_result` template takes any number of exception types. All exception types thrown by the passed function are caught, and an attempt is made to convert the exception object to each of the specified types. Each successfully-converted slice of the caught exception object, as well as the return value of `std::current_exception`, are copied and <>, and in the end the exception is converted to a `<>` object.
(In our example, `error_a` and `error_b` slices as communicated as error objects, but `error_c` exceptions will still 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:
[source,c++]
----
leaf::result print_answer() noexcept
{
BOOST_LEAF_AUTO(answer, compute_answer());
std::cout << "Answer: " << answer << std::endl;
return { };
}
----
[.text-right]
<> | <>
Finally, here is the scope that handles the errors -- it will work correctly regardless of whether `error_a` and `error_b` objects are thrown as exceptions or not.
[source,c++]
----
leaf::try_handle_all(
[]() -> leaf::result
{
BOOST_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;
} );
----
[.text-right]
<> | <> | <>
NOTE: The complete program illustrating this technique is available https://github.com/boostorg/leaf/blob/master/example/exception_to_result.cpp?ts=4[here].
'''
[[tutorial-on_error_in_c_callbacks]]
=== Using `error_monitor` to Report Arbitrary Errors from C-callbacks
Communicating information pertaining to a failure detected in a C callback is tricky, because C callbacks are limited to a specific function signature, which may not use {CPP} types.
LEAF makes this easy. As an example, we'll write a program that uses Lua and reports a failure from a {CPP} function registered as a C callback, called from a Lua program. The failure will be propagated from {CPP}, through the Lua interpreter (written in C), back to the {CPP} function which called it.
C/{CPP} functions designed to be invoked from a Lua program must use the following signature:
[source,c]
----
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 a function, `do_work`, as a C callback available for Lua programs to call:
[source,c++]
----
std::shared_ptr init_lua_state() noexcept
{
std::shared_ptr 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` {CPP} 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` {CPP} 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:
[source,c++]
----
enum do_work_error_code
{
ec1=1,
ec2
};
----
We're now ready to define the `do_work` callback function:
[source,c++]
----
int do_work( lua_State * L ) noexcept
{
bool success = rand() % 2; <1>
if( success )
{
lua_pushnumber(L, 42); <2>
return 1;
}
else
{
(void) leaf::new_error(ec1); <3>
return luaL_error(L, "do_work_error"); <4>
}
}
----
[.text-right]
<> | <>
<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`, 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 `<>`, so that our caller can get the answer in case of success, or an error:
[source,c++]
----
leaf::result call_lua( lua_State * L )
{
lua_getfield(L, LUA_GLOBALSINDEX, "call_do_work");
error_monitor cur_err;
if( int err = lua_pcall(L, 0, 1, 0) ) <1>
{
auto load = leaf::on_error(e_lua_error_message{lua_tostring(L,1)}); <2>
lua_pop(L,1);
return cur_err.assigned_error_id().load(e_lua_pcall_error{err}); <3>
}
else
{
int answer = lua_tonumber(L, -1); <4>
lua_pop(L, 1);
return answer;
}
}
----
[.text-right]
<> | <> | <>
<1> Ask the Lua interpreter to call the global Lua function `call_do_work`.
<2> `on_error` works as usual.
<3> `load` will use the `error_id` generated in our Lua callback. This is the same `error_id` the `on_error` 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:
[source,c++]
----
int main() noexcept
{
std::shared_ptr L=init_lua_state();
for( int i=0; i!=10; ++i )
{
leaf::try_handle_all(
[&]() -> leaf::result
{
BOOST_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;
} );
}
----
[.text-right]
<