]
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, configurable 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] >| 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
Typically, error handling libraries define a variant result type, e.g. `result`. In LEAF we drop the `E`, using just `result`.
In case of success, access to the value `T` is immediate and direct, and we can easily bail out in case of a failure.
To handle errors, we use a special syntax, which enables error objects to be transported directly to the error handling scopes that need them. This is more efficient than holding them in result types, and it also allows any given handler to access multiple error objects associated with the same failure.
LEAF is also compatible with exception handling, providing identical functionality but without needing a result type.
=== Reporting Errors
Let's introduce the `result`-based interface first.
Report errors with `leaf::new_error`:
[source,c++]
----
enum class api_error { connect_failed, invalid_request, timeout };
leaf::result connect()
{
....
if( <> )
return leaf::new_error( api_error::connect_failed ); // Pass error objects of any type
// Produce and return a connection object.
}
----
[.text-right]
<> | <>
'''
[[checking_for_errors]]
=== Checking for Errors
To bail out on failure, return `result::error()`:
[source,c++]
----
leaf::result connect_and_fetch_data()
{
leaf::result cr = connect();
if( !cr )
return cr.error();
connection & c = cr.value();
// Use c to fetch and return data
}
----
[.text-right]
<>
Use `BOOST_LEAF_AUTO` to avoid the boilerplate `if` statement:
[source,c++]
----
leaf::result connect_and_fetch_data()
{
BOOST_LEAF_AUTO(c, connect()); // Bail out on error
// Use c to fetch and return data
}
----
[.text-right]
<>
Use `BOOST_LEAF_CHECK` in case of `void` results:
[source,c++]
----
leaf::result flush(connection & c);
leaf::result bytes_sent(connection & c);
leaf::result flush_and_get_bytes_sent(connection & c)
{
BOOST_LEAF_CHECK(flush(c)); // Bail out on error
return bytes_sent(c);
}
----
[.text-right]
<>
On implementations that define `pass:[__GNUC__]` (e.g. GCC/clang), `BOOST_LEAF_CHECK` is compatible with non-`void` results as well:
[source,c++]
----
leaf::result count_rows();
float update_average(int n);
leaf::result average_row_count()
{
return update_average( BOOST_LEAF_CHECK(count_rows()) );
}
----
The following is the portable alternative:
[source,c++]
----
leaf::result average_row_count()
{
BOOST_LEAF_AUTO(n, count_rows());
return update_average(n);
}
----
'''
[[tutorial-error_handling]]
=== Error Handling
Error handling scopes use a special syntax to indicate that they need to access error objects:
[source,c++]
----
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(c, connect());
return fetch(c);
},
[]( api_error e ) -> leaf::result
{
if( e == api_error::connect_failed )
.... // Handle api_error::connect_failed
else
.... // Handle any other api_error 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 `api_error`. 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 `api_error`). 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(c, connect());
return fetch(c);
},
[]( leaf::match ) -> leaf::result
{
// Handle api_error::connect_failed or api_error::timeout
},
[]( api_error e ) -> leaf::result
{
// Handle any other api_error 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 `api_error` is available, and its value is either `api_error::connect_failed` or `api_error::timeout`.
* Otherwise the second error handler will be called iff an error object of type `api_error` 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(c, connect());
return fetch(c);
},
[]( api_error e, leaf::error_info const & ei ) -> leaf::result
{
if( e == api_error::timeout )
return cached_data();
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++]
----
data r = leaf::try_handle_all(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(c, connect());
return fetch(c);
},
[]( leaf::match ) -> data
{
// Handle api_error::connect_failed
},
[]( api_error e ) -> data
{
// Handle any other api_error value
},
[]() -> data
{
// 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 object rather than a `leaf::result`, so that `leaf::try_handle_all` is guaranteed to succeed.
'''
=== Working with Different Error Types
It is of course possible to provide different handlers for different error types:
[source,c++]
----
enum class api_error { connect_failed, invalid_request, timeout };
enum class auth_error { unauthorized, forbidden };
....
leaf::result r = leaf::try_handle_some(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(c, connect());
return fetch(c);
},
[]( api_error e ) -> leaf::result
{
// Handle errors of type `api_error`.
},
[]( auth_error e ) -> leaf::result
{
// Handle errors of type `auth_error`.
} );
----
[.text-right]
<> | <> | <>
Error handlers are always considered in order:
* The first error handler will be used if an error object of type `api_error` is available;
* otherwise, the second error handler will be used if an error object of type `auth_error` 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_ an 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 available;
* 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 << "I/O 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 << "I/O 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 << "I/O 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 would `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 api_error { connect_failed, invalid_request, timeout };
enum class auth_error { unauthorized, forbidden };
....
leaf::result f()
{
....
if( error_detected )
return leaf::new_error(api_error::connect_failed, auth_error::forbidden);
// Produce and return a T.
}
----
[.text-right]
<> | <>
When using exception handling this becomes:
[source,c++]
----
enum class api_error { connect_failed, invalid_request, timeout };
enum class auth_error { unauthorized, forbidden };
T f()
{
if( error_detected )
leaf::throw_exception(api_error::connect_failed, auth_error::forbidden);
// 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 standard 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!"), api_error::connect_failed, auth_error::forbidden);
----
In this case the thrown exception object will be of a 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, an 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 low 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_some`, `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 instead of an error object we pass a function that returns an error object, that function will only be called if the object it returns is needed, that is, if it will not be discarded. This is helpful when the error object is relatively expensive to produce:
+
[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 reference 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 could use the <> type, which is a simple struct that wraps an `int`. But, we can't just pass an <> to `on_error`, because at that time `errno` 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 validation_error
{
empty_field = 1,
invalid_format,
out_of_range
};
----
We could handle `validation_error` errors like so:
[source,c++]
----
return leaf::try_handle_some(
[]
{
return validate_input(); // Returns leaf::result
},
[]( validation_error e )
{
switch(e)
{
case validation_error::empty_field:
....; // Handle empty_field errors
break;
case validation_error::invalid_format:
case validation_error::out_of_range:
....; // Handle invalid_format and out_of_range errors
break;
default:
....; // Handle unexpected validation_error values
break;
}
} );
----
If a `validation_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 validate_input(); // Returns leaf::result
},
[]( leaf::match m )
{
assert(m.matched == validation_error::empty_field);
....;
},
[]( leaf::match m )
{
assert(m.matched == validation_error::invalid_format || m.matched == validation_error::out_of_range);
....;
},
[]( validation_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 equivalent 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++]
----
config cfg = leaf::try_handle_all(
[&]
{
return load_config_file(config_path); // returns leaf::result
},
[](api_error e) -> config
{
....
},
[](io_error e, e_file_name const & fn) -> config
{
....
},
[]() -> config
{
....
});
----
[.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++]
----
config cfg = leaf::try_handle_all(
[&]
{
return load_config_file(fallback_path); // returns leaf::result
},
[](api_error e) -> config
{
....
},
[](io_error e, e_file_name const & fn) -> config
{
....
},
[]() -> config
{
....
});
----
That works, but it is also possible to bind the error handlers in a `std::tuple`:
[source,c++]
----
auto load_config_error_handlers = std::make_tuple(
[](api_error e) -> config
{
....
},
[](io_error e, e_file_name const & fn) -> config
{
....
},
[]() -> config
{
....
});
----
The `load_config_error_handlers` tuple can later be used with any error handling function:
[source,c++]
----
config cfg1 = leaf::try_handle_all(
[&]
{
return load_config_file(config_path); // <1>
},
load_config_error_handlers );
config cfg2 = leaf::try_handle_all(
[&]
{
return load_config_file(fallback_path); // <2>
},
load_config_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 `load_config_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_exceptions.cpp?ts=4[try_capture_all_exceptions.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`
When integrating a library that throws exceptions into code that uses `result`, use `exception_to_result` to convert exceptions at the boundary:
[source,c++]
----
struct parse_error: std::exception { };
struct syntax_error: parse_error { };
struct encoding_error: parse_error { };
json_value parse_json(char const * str); // Throws parse_error
leaf::result safe_parse_json(char const * str) noexcept
{
return leaf::exception_to_result(
[&]
{
return parse_json(str);
} );
}
----
[.text-right]
<> | <>
The template arguments specify which exception types to capture as error objects. All exceptions are caught, and for each type listed, LEAF attempts a `dynamic_cast` and loads a copy of that slice. The `std::current_exception()` is also captured, so unlisted exception types can still be handled.
Errors can then be handled normally:
[source,c++]
----
leaf::try_handle_all(
[]() -> leaf::result
{
BOOST_LEAF_AUTO(doc, safe_parse_json(input));
process(doc);
return { };
},
[](syntax_error const &)
{
std::cerr << "JSON syntax error" << std::endl;
},
[](encoding_error const &)
{
std::cerr << "Invalid encoding" << std::endl;
},
[]
{
std::cerr << "Unknown error" << std::endl;
} );
----
[.text-right]
<> | <> | <>
TIP: Handlers that take exception types work the same way whether the object was thrown or loaded via `exception_to_result`.
'''
[[tutorial-on_error_in_c_callbacks]]
=== Using `error_monitor` to Report Errors from C Callbacks
C callbacks have fixed signatures that cannot return {CPP} types like `leaf::result`. The <> class solves this problem.
Consider a C library that invokes a user-provided callback:
[source,c++]
----
enum class parse_error { unexpected_token, invalid_syntax };
int on_element(void * ctx, char const * data)
{
if( <> )
{
leaf::new_error(parse_error::unexpected_token);
return -1;
}
return 0;
}
----
[.text-right]
<>
The callback calls `new_error` to associate error objects with the failure, then returns an error code to the C library. The wrapper function uses `error_monitor` to retrieve the `error_id`:
[source,c++]
----
leaf::result parse(char const * input)
{
leaf::error_monitor cur_err;
if( c_library_parse(input, &on_element, nullptr) != 0 )
return cur_err.assigned_error_id();
else
return make_document();
}
----
[.text-right]
<> | <>
If `new_error` was called inside the callback, `assigned_error_id` returns that `error_id`. Otherwise, it calls `new_error` and returns a fresh `error_id`. Either way, the caller can handle the failure normally.
'''
[[tutorial-diagnostic_information]]
=== Diagnostic Information
LEAF is able to automatically generate diagnostic messages that include information about all error objects available to error handlers:
[source,c++]
----
enum class error_code
{
read_error,
write_error
};
....
leaf::try_handle_all(
[]() -> leaf::result <1>
{
....
return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } );
},
[]( leaf::match ) <2>
{
std::cerr << "Read error!" << std::endl;
},
[]( leaf::diagnostic_details const & info ) <3>
{
std::cerr << "Unrecognized error detected\n" << info;
} );
----
<1> We handle all failures that occur in this try block.
<2> One or more error handlers that should handle all possible failures.
<3> This "catch all" error handler is required by `try_handle_all`. It will be called if LEAF is unable to use another error handler.
The `diagnostic_details` output for the snippet above tells us that we got an `error_code` with value `1` (`write_error`), and an object of type `e_file_name` with `"file.txt"` stored in its `.value`:
----
Unrecognized error detected
Error with serial #1
Caught:
error_code: 1
Diagnostic details:
boost::leaf::e_file_name: file.txt
----
TIP: In the `diagnostic_details` output, the section under `Caught:` lists the objects which error handlers take as arguments -- these are the objects which are stored on the stack. The section under `Diagnostic details:` lists all other objects that were communicated. These are the objects that would have been discarded if we didn't provide a handler that takes `diagnostic_details`.
To print each error object, LEAF attempts to bind an unqualified call to `operator<<`, passing a `std::ostream` and the error object. If that fails, it will also attempt to bind `operator<<` that takes the `.value` of the error type. If that also does not compile, the error object value will not appear in diagnostic messages, though LEAF will still print its type.
Even with error types that define a printable `.value`, the user may still want to overload `operator<<` for the enclosing `struct`, e.g.:
[source,c++]
----
struct e_errno
{
int value;
friend std::ostream & operator<<( std::ostream & os, e_errno const & e )
{
return os << e.value << ", \"" << strerror(e.value) << '"';
}
};
----
The `e_errno` type above is designed to hold `errno` values. The defined `operator<<` overload will automatically include the output from `strerror` when `e_errno` values are printed (LEAF defines `e_errno` in ``, together with other commonly used error types).
Using `diagnostic_details` comes at a cost. Normally, when the program attempts to communicate error objects of types which are not used in any error handling scope in the current call stack, they are discarded, which saves cycles. However, if an error handler is provided that takes `diagnostic_details` argument, such objects are stored on the heap instead of being discarded.
If handling `diagnostic_details` is considered too costly, use `diagnostic_info` instead:
[source,c++]
----
leaf::try_handle_all(
[]() -> leaf::result
{
....
return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } );
},
[]( leaf::match )
{
std::cerr << "Read error!" << std::endl;
},
[]( leaf::diagnostic_info const & info )
{
std::cerr << "Unrecognized error detected\n" << info;
} );
----
In this case, the output may look like this:
----
Unrecognized error detected
Error serial #1
Caught:
error_code: 1
----
Notice how we are missing the `Diagnostic details:` section. That's because the `e_file_name` object was discarded by LEAF, since no error handler needed it.
TIP: The automatically generated diagnostic messages are developer-friendly, but not user-friendly.
'''
[[tutorial-serialization]]
=== Serialization
LEAF provides a serialization API that enables exporting error information into different formats, such as JSON. This is useful for structured logging, remote debugging, or integrating with monitoring systems. To serialize error information, use the `output_to` member function available on the following types:
* <>
* <>
* <>
* <>
LEAF serialization is defined in terms of `output` and `output_at` function calls, found via ADL:
* `output(e, x)` serializes `x` directly to encoder `e` as a value.
* `output_at(e, x, name)` serializes `x` to encoder `e` as a named field.
LEAF provides generic `output` overloads for the following types:
* `error_id`
* `e_source_location`
* `e_errno`
* `std::error_code`
* `std::error_condition`
* `std::exception`
* `std::exception_ptr`
* any type with a `.value` member for which a suitable `output` can be found via ADL
[[custom-encoders]]
==== Custom Encoders
To support exporting to a specific format, users define an encoder class with associated `output` and `output_at` function templates specific to that encoder:
[source,c++]
----
struct my_encoder
{
template
friend void output(my_encoder & e, T const & x)
{
// output value x to e
}
template
friend void output_at(my_encoder & e, T const & x, char const * name)
{
// output x to e as a named field
}
};
----
The `output_at` function typically creates a nested scope (e.g. a JSON object or XML element) and then makes an unqualified call to `output` to output the value. This will call any compatible overload found via ADL.
TIP: The `output` function may need to be defined using SFINAE to avoid ambiguities with the generic `output` overloads provided by LEAF. Custom encoders must also handle types that do not provide ADL `output` overloads, including built-in types like `int` and `std::string`.
To enable serialization to a custom encoder type, define a `serialize` function template in the `boost::leaf::serialization` namespace:
[source,c++]
----
namespace boost { namespace leaf {
namespace serialization {
template
void serialize(Handle & h, T const & x, char const * name)
{
h.dispatch([&](my_encoder & e) {
output_at(e, x, name);
});
}
}
} }
----
The `serialize` function template takes a handle reference `h` (of unspecified type) that holds an encoder, the error object to be serialized, and its type name. Call `h.dispatch` with a single-argument function F to detect the encoder type based on F's argument type; F is called only if the handle contains an encoder of that type.
To support multiple output formats, pass multiple functions to `h.dispatch`:
[source,c++]
----
h.dispatch(
[&](json_encoder_nlohmann & e) { output_at(e, x, name); },
[&](xml_encoder & xe) { output_at(xe, x, name); }
);
----
==== JSON Serialization
LEAF provides encoders for JSON serialization with two popular JSON libraries:
* <> for https://github.com/nlohmann/json[nlohmann/json]
* <> for https://www.boost.org/doc/libs/release/libs/json/[Boost.JSON]
Below is an example using `json_encoder_nlohmann`. We just need to define the required `serialize` function template (see <>):
[source,c++]
----
#include
#include "nlohmann/json.hpp"
namespace leaf = boost::leaf;
using json_encoder_nlohmann = leaf::serialization::json_encoder_nlohmann;
namespace boost { namespace leaf {
namespace serialization {
template
void serialize(Handle & h, T const & x, char const * name)
{
h.dispatch([&](json_encoder_nlohmann & e) {
output_at(e, x, name);
});
}
}
} }
----
With this in place, we can easily (for example) output <> to JSON:
[source,c++]
----
struct e_api_response
{
int status;
std::string message;
template
friend void to_json(Json & j, e_api_response const & e)
{
j["status"] = e.status;
j["message"] = e.message;
}
};
struct e_request_url
{
std::string value;
};
....
leaf::try_handle_all(
[]() -> leaf::result
{
....
return leaf::new_error(e_api_response{403, "Access denied"}, e_request_url{"/api/admin/settings"});
},
[](leaf::diagnostic_details const & dd)
{
nlohmann::json j;
json_encoder_nlohmann e(j);
dd.output_to(e);
std::cout << j.dump(2) << std::endl;
}
);
----
.Output:
[source,json]
----
{
"e_api_response": {
"status": 403,
"message": "Access denied"
},
"e_request_url": "/api/admin/settings"
}
----
[.text-right]
<