]
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:
====
* Small single-header format, no dependencies.
* Designed for maximum efficiency ("happy" path and "sad" path).
* No dynamic memory allocations, even with heavy payloads.
* O(1) transport of arbitrary error types (independent of call stack depth).
* Can be used with or without exception handling.
* Support for multi-thread programming.
====
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::[]
LEAF is designed with a strong bias towards the common use case where callers of functions which may fail check for success and forward errors up the call stack but do not handle them. In this case, only a trivial success-or-failure discriminant is transported. Actual error objects are communicated directly to the error-handling scope, skipping the intermediate check-only frames altogether.
[[support]]
== Support
* https://Cpplang.slack.com[cpplang on Slack] (use the `#boost` channel)
* https://lists.boost.org/mailman/listinfo.cgi/boost-users[Boost Users Mailing List]
* https://lists.boost.org/mailman/listinfo.cgi/boost[Boost Developers Mailing List]
* https://github.com/boostorg/leaf/issues[Report an issue] on GitHub
[[portability]]
== Portability
LEAF requires only {CPP}11, but is tested on many compiler versions and C++ standards.
The library uses thread-local storage, except when multi-threading is disabled (e.g. on some embedded platforms). See <>.
[[distribution]]
== Distribution
Copyright (C) 2018-2021 Emil Dotchevski. 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.
* The source code is hosted on https://github.com/boostorg/leaf[GitHub].
* For maximum portability, the library is also available in single-header format: simply download link:leaf.hpp[leaf.hpp] (direct download link).
NOTE: LEAF does not depend on Boost or other libraries.
[[introduction]]
== Five Minute Introduction
We'll implement two versions of the same simple program: one using the LEAF `noexcept` API to handle errors, and another using the exception-handling API.
[[introduction-result]]
=== `noexcept` API
We'll write a short but complete program that reads a text file in a buffer and prints it to `std::cout`, using LEAF to handle errors without exception handling.
NOTE: LEAF provides an <> as well.
We'll skip to the chase and start with the `main` function: it will try several operations as needed and handle all the errors that occur. Did I say *all* the errors? I did, so we'll use `leaf::try_handle_all`. It has the following signature:
[source,c++]
----
template
<> try_handle_all( TryBlock && try_block, Handler && ... handler );
----
`TryBlock` is a function type, required to return a `result` -- for example, `leaf::result` -- that holds a value of type `T` or else indicates a failure.
The first thing `try_handle_all` does is invoke the `try_block` function. If the returned object `r` indicates success, `try_handle_all` unwraps it, returning the contained `r.value()`; otherwise it calls the [underline]#first suitable# error handling function from the `handler...` list.
We'll see later just what kind of a `TryBlock` will our `main` function pass to `try_handle_all`, but first, let's look at the juicy error-handling part. In case of an error, LEAF will consider each of the error handlers, [underline]#in order#, and call the first suitable match:
[source,c++]
----
int main( int argc, char const * argv[] )
{
return leaf::try_handle_all(
[&]() -> leaf::result
{
// The TryBlock goes here, we'll see it later
},
// Error handlers below:
[](leaf::match, leaf::match_value, leaf::e_file_name const & fn)
{ <1>
std::cerr << "File not found: " << fn.value << std::endl;
return 1;
},
[](leaf::match, leaf::e_errno const & errn, leaf::e_file_name const & fn)
{ <2>
std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl;
return 2;
},
[](leaf::match, leaf::e_errno const * errn, leaf::e_file_name const & fn)
{ <3>
std::cerr << "Failed to access " << fn.value;
if( errn )
std::cerr << ", errno=" << *errn;
std::cerr << std::endl;
return 3;
},
[](leaf::match, leaf::e_errno const & errn)
{ <4>
std::cerr << "Output error, errno=" << errn << std::endl;
return 4;
},
[](leaf::match)
{ <5>
std::cout << "Bad command line argument" << std::endl;
return 5;
},
[](leaf::error_info const & unmatched)
{ <6>
std::cerr <<
"Unknown failure detected" << std::endl <<
"Cryptic diagnostic information follows" << std::endl <<
unmatched;
return 6;
}
);
}
----
<1> This handler will be called if the detected error includes: +
pass:[•] an object of type `enum error_code` equal to the value `open_error`, and +
pass:[•] an object of type `leaf::e_errno` that has `.value` equal to `ENOENT`, and +
pass:[•] an object of type `leaf::e_file_name`. +
In short, it handles "file not found" errors.
<2> This handler will be called if the detected error includes: +
pass:[•] an object of type `enum error_code` equal to `open_error`, and +
pass:[•] an object of type `leaf::e_errno` (regardless of its `.value`), and +
pass:[•] an object of type `leaf::e_file_name`. +
In short, it will handle other "file open" errors.
<3> This handler will be called if the detected error includes: +
pass:[•] an object of type `enum error_code` equal to any of `size_error`, `read_error`, `eof_error`, and +
pass:[•] an optional object of type `leaf::e_errno` (regardless of its `.value`), and +
pass:[•] an object of type `leaf::e_file_name`.
<4> This handler will be called if the detected error includes: +
pass:[•] an object of type `enum error_code` equal to `output_error`, and +
pass:[•] an object of type `leaf::e_errno` (regardless of its `.value`),
<5> This handler will be called if the detected error includes an object of type `enum error_code` equal to `bad_command_line`.
<6> This last handler is a catch-all for any error, in case no other handler could be selected: it prints diagnostic information to help debug logic errors in the program, since it failed to find an appropriate error handler for the error condition it encountered.
WARNING: It is critical to understand that the error handlers are considered in order, rather than by finding a "best match". No error handler is "better" than the others: LEAF will call the first one for which all of the arguments can be supplied using the available error objects.
Now, reading and printing a file may not seem like a complex job, but let's split it into several functions, each communicating failures using `leaf::result`:
[source,c++]
----
leaf::result parse_command_line( int argc, char const * argv[] ) noexcept; <1>
leaf::result> file_open( char const * file_name ) noexcept; <2>
leaf::result file_size( FILE & f ) noexcept; <3>
leaf::result file_read( FILE & f, void * buf, int size ) noexcept; <4>
----
<1> Parse the command line, return the file name.
<2> Open a file for reading.
<3> Return the size of the file.
<4> Read size bytes from f into buf.
For example, let's look at `file_open`:
[source,c++]
----
leaf::result> file_open( char const * file_name ) noexcept
{
if( FILE * f = fopen(file_name,"rb") )
return std::shared_ptr(f,&fclose);
else
return leaf::new_error(open_error, leaf::e_errno{errno});
}
----
If `fopen` succeeds, we return a `shared_ptr` which will automatically call `fclose` as needed. If `fopen` fails, we report an error by calling `new_error`, which takes any number of error objects to communicate with the error. In this case we pass the system `errno` (LEAF defines `struct e_errno {int value;}`), and our own error code value, `open_error`.
Here is our complete error code `enum`:
[source,c++]
----
enum error_code
{
bad_command_line = 1,
open_error,
read_error,
size_error,
eof_error,
output_error
};
----
We're now ready to look at the `TryBlock` we'll pass to `try_handle_all`. It does all the work, bails out if it encounters an error:
[source,c++]
----
int main( int argc, char const * argv[] )
{
return leaf::try_handle_all(
[&]() -> leaf::result
{
leaf::result file_name = parse_command_line(argc,argv);
if( !file_name )
return file_name.error();
----
Wait, what's this, if "error" return "error"? There is a better way: we'll use `BOOST_LEAF_AUTO`. It takes a `result` and bails out in case of a failure (control leaves the calling function), otherwise uses the passed variable to access the `T` value stored in the `result` object.
This is what our `TryBlock` really looks like:
[source,c++]
----
int main( int argc, char const * argv[] )
{
return leaf::try_handle_all(
[&]() -> leaf::result <1>
{
BOOST_LEAF_AUTO(file_name, parse_command_line(argc,argv)); <2>
auto load = leaf::on_error( leaf::e_file_name{file_name} ); <3>
BOOST_LEAF_AUTO(f, file_open(file_name)); <4>
BOOST_LEAF_AUTO(s, file_size(*f)); <4>
std::string buffer( 1 + s, '\0' );
BOOST_LEAF_CHECK(file_read(*f, &buffer[0], buffer.size()-1)); <4>
std::cout << buffer;
std::cout.flush();
if( std::cout.fail() )
return leaf::new_error(output_error, leaf::e_errno{errno});
return 0;
},
.... <5>
); <6>
}
----
<1> Our `TryBlock` returns a `result`. In case of success, it will hold `0`, which will be returned from `main` to the OS.
<2> If `parse_command_line` returns an error, we forward that error to `try_handle_all` (which invoked us) verbatim. Otherwise, `BOOST_LEAF_AUTO` gets us a variable, `file_name`, to access the parsed string.
<3> From now on, all errors escaping this scope will automatically communicate the (now successfully parsed from the command line) file name (LEAF defines `struct e_file_name {std::string value;}`). This is as if every time one of the following functions wants to report an error, `on_error` says "wait, associate this `e_file_name` object with the error, it's important!"
<4> Call more functions, forward each failure to the caller.
<5> List of error handlers goes here (we saw this earlier).
<6> This concludes the `try_handle_all` arguments -- as well as our program!
Nice and simple! Writing the `TryBlock`, we focus on the "happy" path -- if we encounter any error we just return it to `try_handle_all` for processing. Well, that's if we're being good and using RAII for automatic clean-up -- which we are, `shared_ptr` will automatically close the file for us.
TIP: The complete program from this tutorial is available https://github.com/boostorg/leaf/blob/master/examples/print_file/print_file_result.cpp?ts=4[here]. The https://github.com/boostorg/leaf/blob/master/examples/print_file/print_file_eh.cpp?ts=4[other] version of the same program uses exception handling to report errors (see <>).
'''
[[introduction-eh]]
=== Exception-Handling API
And now, we'll write the same program that reads a text file in a buffer and prints it to `std::cout`, this time using exceptions to report errors. First, we need to define our exception class hierarchy:
[source,c++]
----
struct bad_command_line: std::exception { };
struct input_error: std::exception { };
struct open_error: input_error { };
struct read_error: input_error { };
struct size_error: input_error { };
struct eof_error: input_error { };
struct output_error: std::exception { };
----
We'll split the job into several functions, communicating failures by throwing exceptions:
[source,c++]
----
char const * parse_command_line( int argc, char const * argv[] ); <1>
std::shared_ptr file_open( char const * file_name ); <2>
int file_size( FILE & f ); <3>
void file_read( FILE & f, void * buf, int size ); <4>
----
<1> Parse the command line, return the file name.
<2> Open a file for reading.
<3> Return the size of the file.
<4> Read size bytes from f into buf.
The `main` function brings everything together and handles all the exceptions that are thrown, but instead of using `try` and `catch`, it will use the function template `leaf::try_catch`, which has the following signature:
[source,c++]
----
template
<> try_catch( TryBlock && try_block, Handler && ... handler );
----
`TryBlock` is a function type that takes no arguments; `try_catch` simply returns the value returned by the `try_block`, catching [underline]#any# exception it throws, in which case it calls the [underline]#first# suitable error handling function from the `handler...` list.
Let's first look at the `TryBlock` our `main` function passes to `try_catch`:
[source,c++]
----
int main( int argc, char const * argv[] )
{
return leaf::try_catch(
[&] <1>
{
char const * file_name = parse_command_line(argc,argv); <2>
auto load = leaf::on_error( leaf::e_file_name{file_name} ); <3>
std::shared_ptr f = file_open( file_name ); <2>
std::string buffer( 1+file_size(*f), '\0' ); <2>
file_read(*f, &buffer[0], buffer.size()-1); <2>
std::cout << buffer;
std::cout.flush();
if( std::cout.fail() )
throw leaf::exception(output_error{}, leaf::e_errno{errno});
return 0;
},
.... <4>
); <5>
}
----
<1> Except if it throws, our `TryBlock` returns `0`, which will be returned from `main` to the OS.
<2> If any of the functions we call throws, `try_catch` will find an appropriate handler to invoke (below).
<3> From now on, all exceptions escaping this scope will automatically communicate the (now successfully parsed from the command line) file name (LEAF defines `struct e_file_name {std::string value;}`). This is as if every time one of the following functions wants to throw an exception, `on_error` says "wait, associate this `e_file_name` object with the exception, it's important!"
<4> List of error handlers goes here. We'll see that later.
<5> This concludes the `try_catch` arguments -- as well as our program!
As it is always the case when using exception handling, as long as our `TryBlock` is exception-safe, we can focus on the "happy" path. Of course, our `TryBlock` is exception-safe, since `shared_ptr` will automatically close the file for us in case an exception is thrown.
Now let's look at the second part of the call to `try_catch`, which lists the error handlers:
[source,c++]
----
int main( int argc, char const * argv[] )
{
return leaf::try_catch(
[&]
{
// The TryBlock goes here (we saw that earlier)
},
// Error handlers below:
[](open_error &, leaf::match_value, leaf::e_file_name const & fn)
{ <1>
std::cerr << "File not found: " << fn.value << std::endl;
return 1;
},
[](open_error &, leaf::e_file_name const & fn, leaf::e_errno const & errn)
{ <2>
std::cerr << "Failed to open " << fn.value << ", errno=" << errn << std::endl;
return 2;
},
[](input_error &, leaf::e_errno const * errn, leaf::e_file_name const & fn)
{ <3>
std::cerr << "Failed to access " << fn.value;
if( errn )
std::cerr << ", errno=" << *errn;
std::cerr << std::endl;
return 3;
},
[](output_error &, leaf::e_errno const & errn)
{ <4>
std::cerr << "Output error, errno=" << errn << std::endl;
return 4;
},
[](bad_command_line &)
{ <5>
std::cout << "Bad command line argument" << std::endl;
return 5;
},
[](leaf::error_info const & unmatched)
{ <6>
std::cerr <<
"Unknown failure detected" << std::endl <<
"Cryptic diagnostic information follows" << std::endl <<
unmatched;
return 6;
} );
}
----
<1> This handler will be called if: +
pass:[•] an `open_error` exception was caught, with +
pass:[•] an object of type `leaf::e_errno` that has `.value` equal to `ENOENT`, and +
pass:[•] an object of type `leaf::e_file_name`. +
In short, it handles "file not found" errors.
<2> This handler will be called if: +
pass:[•] an `open_error` exception was caught, with +
pass:[•] an object of type `leaf::e_errno` (regardless of its `.value`), and +
pass:[•] an object of type `leaf::e_file_name`. +
In short, it handles other "file open" errors.
<3> This handler will be called if: +
pass:[•] an `input_error` exception was caught (which is a base type), with +
pass:[•] an optional object of type `leaf::e_errno` (regardless of its `.value`), and +
pass:[•] an object of type `leaf::e_file_name`.
<4> This handler will be called if: +
pass:[•] an `output_error` exception was caught, with +
pass:[•] an object of type `leaf::e_errno` (regardless of its `.value`),
<5> This handler will be called if a `bad_command_line` exception was caught.
<6> If `try_catch` fails to find an appropriate handler, it will re-throw the exception. But this is the `main` function which should handle all exceptions, so this last handler matches any error and prints diagnostic information, to help debug logic errors.
WARNING: It is critical to understand that the error handlers are considered in order, rather than by finding a "best match". No error handler is "better" than the others: LEAF will call the first one for which all of the arguments can be supplied using the available error objects.
To conclude this introduction, let's look at one of the error-reporting functions that our `TryBlock` calls, for example `file_open`:
[source,c++]
----
std::shared_ptr file_open( char const * file_name )
{
if( FILE * f = fopen(file_name,"rb") )
return std::shared_ptr(f,&fclose);
else
throw leaf::exception(open_error{}, leaf::e_errno{errno});
}
----
If `fopen` succeeds, it returns a `shared_ptr` which will automatically call `fclose` as needed. If `fopen` fails, we throw the exception object returned by `leaf::exception`, which in this case is of type that derives from `open_error`; the passed `e_errno` object will be associated with the exception.
NOTE: `try_catch` works with any exception, not only exceptions thrown using `leaf::exception`.
TIP: The complete program from this tutorial is available https://github.com/boostorg/leaf/blob/master/examples/print_file/print_file_eh.cpp?ts=4[here]. The https://github.com/boostorg/leaf/blob/master/examples/print_file/print_file_result.cpp?ts=4[other] version of the same program does not use exception handling to report errors (see the <>).
[[tutorial]]
== Tutorial
This section assumes the reader has basic understanding of using LEAF to handle errors; see <>.
[[tutorial-model]]
=== Error Communication Model
==== `noexcept` API
The following figure illustrates how error objects are transported when using LEAF without exception handling:
.LEAF noexcept Error Communication Model
image::LEAF-1.png[]
The arrows pointing down indicate the call stack order for the functions `f1` through `f5`: higher level functions calling lower level functions.
Note the call to `on_error` in `f3`: it caches the passed error objects of types `E1` and `E3` in the returned object `load`, where they stay ready to be communicated in case any function downstream from `f3` reports an error. Presumably these objects are relevant to any such failure, but are conveniently accessible only in this scope.
_Figure 1_ depicts the condition where `f5` has detected an error. It calls `leaf::new_error` to create a new, unique `error_id`. The passed error object of type `E2` is immediately loaded in the first active `context` object that provides static storage for it, found in any calling scope (in this case `f1`), and is associated with the newly-generated `error_id` (solid arrow);
The `error_id` itself is returned to the immediate caller `f4`, usually stored in a `result` object `r`. That object takes the path shown by dashed arrows, as each error-neutral function, unable to handle the failure, forwards it to its immediate caller in the returned value -- until an error-handling scope is reached.
When the destructor of the `load` object in `f3` executes, it detects that `new_error` was invoked after its initialization, loads the cached objects of types `E1` and `E3` in the first active `context` object that provides static storage for them, found in any calling scope (in this case `f1`), and associates them with the last generated `error_id` (solid arrow).
When the error-handling scope `f1` is reached, it probes `ctx` for any error objects associated with the `error_id` it received from `f2`, and processes a list of user-provided error handlers, in order, until it finds a handler with arguments that can be supplied using the available (in `ctx`) error objects. That handler is called to deal with the failure.
==== Exception-Handling API
The following figure illustrates the slightly different error communication model used when errors are reported by throwing exceptions:
.LEAF Error Communication Model Using Exception Handling
image::LEAF-2.png[]
The main difference is that the call to `new_error` is implicit in the call to the function template `leaf::exception`, which in this case takes an exception object of type `Ex`, and returns an exception object of unspecified type that derives publicly from `Ex`.
[[tutorial-interoperability]]
==== Interoperability
Ideally, when an error is detected, a program using LEAF would always call <>, ensuring that each encountered failure is definitely assigned a unique <>, which then is reliably delivered, by an exception or by a `result` object, to the appropriate error-handling scope.
Alas, this is not always possible.
For example, the error may need to be communicated through uncooperative 3rd-party interfaces. To facilitate this transmission, a error ID may be encoded in a `std::error_code`. As long as a 3rd-party interface understands `std::error_code`, it should be compatible with LEAF.
Further, it is sometimes necessary to communicate errors through an interface that does not even use `std::error_code`. An example of this is when an external lower-level library throws an exception, which is unlikely to be able to carry an `error_id`.
To support this tricky use case, LEAF provides the function <>, 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.
TIP: To avoid ambiguities, whenever possible, use the <> function template when throwing exceptions to ensure that the exception object transports a unique `error_id`; better yet, use the <> macro, which in addition will capture `pass:[__FILE__]` and `pass:[__LINE__]`.
'''
[[tutorial-loading]]
=== Loading of Error Objects
To load an error object is to move it into an active <>, usually local to a <>, a <> or a <> scope in the calling thread, where it becomes uniquely associated with a specific <> -- or discarded if storage is not available.
Various LEAF functions take a list of error objects to load. As an example, if a function `copy_file` that takes the name of the input file and the name of the output file as its arguments detects a failure, it could communicate an error code `ec`, plus the two relevant file names using <>:
[source,c++]
----
return leaf::new_error(ec, e_input_name{n1}, e_output_name{n2});
----
Alternatively, error objects may be loaded using a `result` that is already communicating an error. This way they become associated with that error, rather than with a new error:
[source,c++]
----
leaf::result f() noexcept;
leaf::result g( char const * fn ) noexcept
{
if( leaf::result r = f() )
{ <1>
....;
return { };
}
else
{
return r.load( e_file_name{fn} ); <2>
}
}
----
[.text-right]
<> | <>
<1> Success! Use `r.value()`.
<2> `f()` has failed; here we associate an additional `e_file_name` with the error. However, this association occurs iff in the call stack leading to `g` there are error handlers that take an `e_file_name` argument. Otherwise, the object passed to `load` is discarded. In other words, the passed objects are loaded iff the program actually uses them to handle errors.
Besides error objects, `load` can take function arguments:
* If we pass a function that takes no arguments, it is invoked, and the returned error object is loaded.
+
Consider that if we pass to `load` an error object that is not needed by any error handler, it will be discarded. If the object is expensive to compute, it would be better if the computation can be skipped as well. Passing a function with no arguments to `load` is an excellent way to achieve this behavior:
+
[source,c++]
----
struct info { .... };
info compute_info() noexcept;
leaf::result operation( char const * file_name ) noexcept
{
if( leaf::result r = try_something() )
{ <1>
....
return { };
}
else
{
return r.load( <2>
[&]
{
return compute_info();
} );
}
}
----
[.text-right]
<> | <>
+
<1> Success! Use `r.value()`.
<2> `try_something` has failed; `compute_info` will only be called if an error handler exists which takes a `info` argument.
+
* If we pass a function that takes a single argument of type `E &`, LEAF calls the function with the object of type `E` currently loaded in an active `context`, associated with the error. If no such object is available, a new one is default-initialized and then passed to the function.
+
For example, if an operation that involves many different files fails, a program may provide for collecting all relevant file names in a `e_relevant_file_names` object:
+
[source,c++]
----
struct e_relevant_file_names
{
std::vector value;
};
leaf::result operation( char const * file_name ) noexcept
{
if( leaf::result r = try_something() )
{ <1>
....
return { };
}
else
{
return r.load( <2>
[&](e_relevant_file_names & e)
{
e.value.push_back(file_name);
} );
}
}
----
[.text-right]
<> | <>
+
<1> Success! Use `r.value()`.
<2> `try_something` has failed -- add `file_name` to the `e_relevant_file_names` object, associated with the `error_id` communicated in `r`. Note, however, that the passed function will only be called iff in the call stack there are error handlers that take an `e_relevant_file_names` object.
'''
[[tutorial-on_error]]
=== Using `on_error`
It is not typical for an error-reporting function to be able to supply all of the data needed by a suitable error-handling function in order to recover from the failure. For example, a function that reports `FILE` operation failures may not have access to the file name, yet an error handling function needs it in order to print a useful error message.
Of course the file name is typically readily available in the call stack leading to the failed `FILE` operation. Below, while `parse_info` can't report the file name, `parse_file` can and does:
[source,c++]
----
leaf::result parse_info( FILE * f ) noexcept; <1>
leaf::result parse_file( char const * file_name ) noexcept
{
auto load = leaf::on_error(leaf::e_file_name{file_name}); <2>
if( FILE * f = fopen(file_name,"r") )
{
auto r = parse_info(f);
fclose(f);
return r;
}
else
return leaf::new_error( error_enum::file_open_error );
}
----
[.text-right]
<> | <> | <>
<1> `parse_info` parses `f`, communicating errors using `result`.
<2> Using `on_error` ensures that the file name is included with any error reported out of `parse_file`. All we need to do is hold on to the returned object `load`; when it expires, if an error is being reported, the passed `e_file_name` value will be automatically associated with it.
TIP: `on_error` -- like `load` -- can be passed any number of arguments.
When we invoke `on_error`, we can pass three kinds of arguments:
. Actual error objects (like in the example above);
. Functions that take no arguments and return an error object;
. Functions that take an error object by mutable reference.
If we want to use `on_error` to capture `errno`, we can't just pass <> to it, because at that time it hasn't been set (yet). Instead, we'd pass a function that returns it:
[source,c++]
----
void read_file(FILE * f) {
auto load = leaf::on_error([]{ return e_errno{errno}; });
....
size_t nr1=fread(buf1,1,count1,f);
if( ferror(f) )
throw leaf::exception();
size_t nr2=fread(buf2,1,count2,f);
if( ferror(f) )
throw leaf::exception();
size_t nr3=fread(buf3,1,count3,f);
if( ferror(f) )
throw leaf::exception();
....
}
----
Above, if a `throw` statement is reached, LEAF will invoke the function passed to `on_error` and associate the returned `e_errno` object with the exception.
The final type of arguments that can be passed to `on_error` is a function that takes a single mutable error object reference. In this case, `on_error` uses it similarly to how such functios are used by `load`; see <>.
'''
[[tutorial-predicates]]
=== Using Predicates to Handle Errors
Usually, LEAF error handlers are selected based on the type of the arguments they take and the type of the available error objects. When an error handler takes a predicate type as an argument, the <> is able to also take into account the _value_ of the available error objects.
Consider this error code enum:
[source,c++]
----
enum class my_error
{
e1=1,
e2,
e3
};
----
We could handle `my_error` errors like so:
[source,c++]
----
return leaf::try_handle_some(
[]
{
return f(); // returns leaf::result
},
[]( my_error e )
{ <1>
switch(e)
{
case my_error::e1:
....; <2>
break;
case my_error::e2:
case my_error::e3:
....; <3>
break;
default:
....; <4>
break;
} );
----
<1> This handler will be selected if we've got a `my_error` object.
<2> Handle `e1` errors.
<3> Handle `e2` and `e3` errors.
<4> Handle bad `my_error` values.
If `my_error` object is available, LEAF will call our error handler. If not, the failure will be forwarded to our caller.
This can be rewritten using the <> predicate to organize the different cases in different error handlers. The following is equivalent:
[source,c++]
----
return leaf::try_handle_some(
[]
{
return f(); // returns leaf::result
},
[]( leaf::match m )
{ <1>
assert(m.matched == my_error::e1);
....;
},
[]( leaf::match m )
{ <2>
assert(m.matched == my_error::e2 || m.matched == my_error::e3);
....;
},
[]( my_error e )
{ <3>
....;
} );
----
<1> We've got a `my_error` object that compares equal to `e1`.
<2> We`ve got a `my_error` object that compares equal to either `e2` or `e3`.
<3> Handle bad `my_error` values.
The first argument to the `match` template generally specifies the type `E` of the error object `e` that must be available for the error handler to be considered at all. Typically, the rest of the arguments are values. The error handler to be dropped if `e` does not compare equal to any of them.
In particular, `match` works great with `std::error_code`. The following handler is designed to handle `ENOENT` errors:
[source,c++]
----
[]( leaf::match )
{
}
----
This, however, requires {CPP}17 or newer, because it is impossible to infer the type of the error enum (in this case, `std::errc`) from the specified type `std::error_code`, and {CPP}11 does not allow `auto` template arguments. LEAF provides the following workaround, compatible with {CPP}11:
[source,c++]
----
[]( leaf::match, std::errc::no_such_file_or_directory> )
{
}
----
In addition, it is possible to select a handler based on `std::error_category`. The following handler will match any `std::error_code` of the `std::generic_category` (requires {CPP}17 or newer):
[source,c++]
----
[]( std::error_code, leaf::category> )
{
}
----
TIP: See <> for more examples.
The following predicates are available:
* <>: as described above.
* <>: where `match` compares the object `e` of type `E` with the values `V...`, `match_value` compare `e.value` with the values `V...`.
* <>: similar to `match_value`, but takes a pointer to the data member to compare; that is, `match_member<&E::value, V...>` is equvialent to `match_value`. Note, however, that `match_member` requires {CPP}17 or newer, while `match_value` does not.
* `<>`: Similar to `match`, but checks whether the caught `std::exception` object can be `dynamic_cast` to any of the `Ex` types.
* <> is a special predicate that takes any other predicate `Pred` and requires that an error object of type `E` is available and that `Pred` evaluates to `false`. For example, `if_not>` requires that an object `e` of type `E` is available, and that it does not compare equal to any of the specified `V...`.
Finally, the predicate system is easily extensible, see <>.
NOTE: See also <>.
'''
[[tutorial-binding_handlers]]
=== Binding Error Handlers in a `std::tuple`
Consider this snippet:
[source,c++]
----
leaf::try_handle_all(
[&]
{
return f(); // returns leaf::result
},
[](my_error_enum x)
{
...
},
[](read_file_error_enum y, e_file_name const & fn)
{
...
},
[]
{
...
});
----
[.text-right]
<> | <>
Looks pretty simple, but what if we need to attempt a different set of operations yet use the same handlers? We could repeat the same thing with a different function passed as `TryBlock` for `try_handle_all`:
[source,c++]
----
leaf::try_handle_all(
[&]
{
return g(); // returns leaf::result
},
[](my_error_enum x)
{
...
},
[](read_file_error_enum y, e_file_name const & fn)
{
...
},
[]
{
...
});
----
That works, but it is better to bind our error handlers in a `std::tuple`:
[source,c++]
----
auto error_handlers = std::make_tuple(
[](my_error_enum x)
{
...
},
[](read_file_error_enum y, e_file_name const & fn)
{
...
},
[]
{
...
});
----
The `error_handlers` tuple can later be used with any error handling function:
[source,c++]
----
leaf::try_handle_all(
[&]
{
// Operations which may fail <1>
},
error_handlers );
leaf::try_handle_all(
[&]
{
// Different operations which may fail <2>
},
error_handlers ); <3>
----
[.text-right]
<> | <>
<1> One set of operations which may fail...
<2> A different set of operations which may fail...
<3> ... both using the same `error_handlers`.
Error-handling functions accept a `std::tuple` of error handlers in place of any error handler. The behavior is as if the tuple is unwrapped in-place.
'''
[[tutorial-async]]
=== Transporting Error Objects Between Threads
Error objects are stored on the stack in an instance of the <> class template in the scope of e.g. <>, <> or <> functions. When using concurrency, we need a mechanism to collect error objects in one thread, then use them to handle errors in another thread.
LEAF offers two interfaces for this purpose, one using `result`, and another designed for programs that use exception handling.
[[tutorial-async_result]]
==== Using `result`
Let's assume we have a `task` that we want to launch asynchronously, which produces a `task_result` but could also fail:
[source,c++]
----
leaf::result task();
----
Because the task will run asynchronously, in case of a failure we need it to capture the relevant error objects but not handle errors. To this end, in the main thread we bind our error handlers in a `std::tuple`, which we will later use to handle errors from each completed asynchronous task (see <>):
[source,c++]
----
auto error_handlers = std::make_tuple(
[](E1 e1, E2 e2)
{
//Deal with E1, E2
....
return { };
},
[](E3 e3)
{
//Deal with E3
....
return { };
} );
----
Why did we start with this step? Because we need to create a <> object to collect the error objects we need. We could just instantiate the `context` template with `E1`, `E2` and `E3`, but that would be prone to errors, since it could get out of sync with the handlers we use. Thankfully LEAF can deduce the types we need automatically, we just need to show it our `error_handlers`:
[source,c++]
----
std::shared_ptr ctx = leaf::make_shared_context(error_handlers);
----
The `polymorphic_context` type is an abstract base class that has the same members as any instance of the `context` class template, allowing us to erase its exact type. In this case what we're holding in `ctx` is a `context`, where `E1`, `E2` and `E3` were deduced automatically from the `error_handlers` tuple we passed to `make_shared_context`.
We're now ready to launch our asynchronous task:
[source,c++]
----
std::future> launch_task() noexcept
{
return std::async(
std::launch::async,
[&]
{
std::shared_ptr ctx = leaf::make_shared_context(error_handlers);
return leaf::capture(ctx, &task);
} );
}
----
[.text-right]
<> | <> | <>
That's it! Later when we `get` the `std::future`, we can process the returned `result` in a call to <>, using the `error_handlers` tuple we created earlier:
[source,c++]
----
//std::future> fut;
fut.wait();
return leaf::try_handle_some(
[&]() -> leaf::result
{
BOOST_LEAF_AUTO(r, fut.get());
//Success!
return { }
},
error_handlers );
----
[.text-right]
<> | <> | <>
The reason this works is that in case it communicates a failure, `leaf::result` is able to hold a `shared_ptr` object. That is why earlier instead of calling `task()` directly, we called `leaf::capture`: it calls the passed function and, in case that fails, it stores the `shared_ptr` we created in the returned `result`, which now doesn't just communicate the fact that an error has occurred, but also holds the `context` object that `try_handle_some` needs in order to supply a suitable handler with arguments.
NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/examples/capture_in_result.cpp?ts=4[capture_in_result.cpp].
'''
[[tutorial-async_eh]]
==== Using Exception Handling
Let's assume we have an asynchronous `task` which produces a `task_result` but could also throw:
[source,c++]
----
task_result task();
----
Just like we saw in <>, first we will bind our error handlers in a `std::tuple`:
[source,c++]
----
auto handle_errors = std::make_tuple(
{
[](E1 e1, E2 e2)
{
//Deal with E1, E2
....
return { };
},
[](E3 e3)
{
//Deal with E3
....
return { };
} );
----
Launching the task looks the same as before, except that we don't use `result`:
[source,c++]
----
std::future launch_task()
{
return std::async(
std::launch::async,
[&]
{
std::shared_ptr ctx = leaf::make_shared_context(&handle_error);
return leaf::capture(ctx, &task);
} );
}
----
[.text-right]
<> | <>
That's it! Later when we `get` the `std::future`, we can process the returned `task_result` in a call to <>, using the `error_handlers` we saved earlier, as if it was generated locally:
[source,c++]
----
//std::future fut;
fut.wait();
return leaf::try_catch(
[&]
{
task_result r = fut.get(); // Throws on error
//Success!
},
error_handlers );
----
[.text-right]
<>
This works similarly to using `result`, except that the `std::shared_ptr` is transported in an exception object (of unspecified type which <> recognizes and then automatically unwraps the original exception).
NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/examples/capture_in_exception.cpp?ts=4[capture_in_exception.cpp].
'''
[[tutorial-classification]]
=== Classification of Failures
It is common for any given 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 contains comments, so we know where to go for reference.
The disadvantage of such flat enums is that they do not support handling a whole class of failures. Consider this error handler from the <>:
[source,c++]
----
....
[](leaf::match, leaf::e_errno const * errn, leaf::e_file_name const & fn)
{
std::cerr << "Failed to access " << fn.value;
if( errn )
std::cerr << ", errno=" << *errn;
std::cerr << std::endl;
return 3;
},
....
----
It will get called if the value of the `error_code` enum communicated with the failure is one of `size_error`, `read_error` or `eof_error`. In short, the idea is to handle any input error.
But what if later we add support for detecting and reporting a new type of input error, e.g. `permissions_error`? It is easy to add that to our `error_code` enum; but now our input error handler won't recognize this new input error -- and we have a bug.
If we can use exceptions, the situation is better because exception types can be organized in a hierarchy in order to classify failures:
[source,c++]
----
struct input_error: std::exception { };
struct read_error: input_error { };
struct size_error: input_error { };
struct eof_error: input_error { };
----
In terms of LEAF, our input error exception handler now looks like this:
[source,c++]
----
[](input_error &, leaf::e_errno const * errn, leaf::e_file_name const & fn)
{
std::cerr << "Failed to access " << fn.value;
if( errn )
std::cerr << ", errno=" << *errn;
std::cerr << std::endl;
return 3;
},
----
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. If we go back to the introduction section, instead of defining:
[source,c++]
----
enum error_code
{
....
read_error,
size_error,
eof_error,
....
};
----
We could define:
[source,c++]
----
....
struct input_error { };
struct read_error { };
struct size_error { };
struct eof_error { };
....
----
With this in place, `file_read` from the https://github.com/boostorg/leaf/blob/master/examples/print_file/print_file_result.cpp?ts=4[print_file_result.cpp] example can be rewritten like this:
[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:
[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) )
throw leaf::exception(read_error{}, leaf::e_errno{errno});
if( n!=size )
throw leaf::exception(eof_error{});
}
----
[.text-right]
<> | <> | <>
NOTE: If the type of the first argument passed to `leaf::exception` derives from `std::exception`, it will be used to initialize the returned exception object taken by `throw`. Here this is not the case, so the function returns a default-initialized `std::exception` object, while the first (and any other) argument is associated with the failure.
And now we can write a future-proof handler that can handle any `input_error`:
[source,c++]
----
....
[](input_error, leaf::e_errno const * errn, leaf::e_file_name const & fn)
{
std::cerr << "Failed to access " << fn.value;
if( errn )
std::cerr << ", errno=" << *errn;
std::cerr << std::endl;
return 3;
},
....
----
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. Here is the complete example from the introduction section, rewritten to use this technique:
* https://github.com/boostorg/leaf/blob/master/examples/print_file/print_file_result_error_tags.cpp?ts=4[print_file_result_error_tags.cpp] (using `leaf::result`).
* https://github.com/boostorg/leaf/blob/master/examples/print_file/print_file_eh_error_tags.cpp?ts=4[print_file_eh_error_tags.cpp] (using exception handling).
'''
[[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.
NOTE: Understand that 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 a 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/examples/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 static 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 `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
{
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]
<> | <> | <> | <>
<1> If the call to `call_lua` succeeded, just print the answer.
<2> Handle `do_work` failures.
<3> Handle all other `lua_pcall` failures.
NOTE: Follow this link to see the complete program: https://github.com/boostorg/leaf/blob/master/examples/lua_callback_result.cpp?ts=4[lua_callback_result.cpp].
TIP: When using Lua with {CPP}, we need to protect the Lua interpreter from exceptions that may be thrown from {CPP} functions installed as `lua_CFunction` callbacks. Here is the program from this section rewritten to use a {CPP} exception to safely communicate errors out of the `do_work` function: https://github.com/boostorg/leaf/blob/master/examples/lua_callback_eh.cpp?ts=4[lua_callback_eh.cpp].
'''
[[tutorial-diagnostic_information]]
=== Diagnostic Information
LEAF is able to automatically generate diagnostic messages that include information about all error objects available to error handlers. For this purpose, it needs to be able to print objects of user-defined error types.
To do this, 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 doesn't 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 << "errno = " << e.value << ", \"" << strerror(e.value) << '"';
}
};
----
The `e_errno` type above is designed to hold `errno` values. The defined `operator<<` overload will automatically include the output from `strerror` when `e_errno` values are printed (LEAF defines `e_errno` in ``, together with other commonly-used error types).
TIP: The automatically-generated diagnostic messages are developer-friendly, but not user-friendly. Therefore, `operator<<` overloads for error types should only print technical information in English, and should not attempt to localize strings or to format a user-friendly message; this should be done in error-handling functions specifically designed for that purpose.
'''
[[tutorial-std_error_code]]
=== Working with `std::error_code`, `std::error_condition`
==== Introduction
The relationship between `std::error_code` and `std::error_condition` is not easily understood from reading the standard specifications. This section explains how they're supposed to be used, and how LEAF interacts with them.
The idea behind `std::error_code` is to encode both an integer value representing an error code, as well as the domain of that value. The domain is represented by a `std::error_category` [underline]#reference#. Conceptually, a `std::error_code` is like a `pair`.
Let's say we have this `enum`:
[source,c++]
----
enum class libfoo_error
{
e1 = 1,
e2,
e3
};
----
We want to be able to transport `libfoo_error` values in `std::error_code` objects. This erases their static type, which enables them to travel freely across API boundaries. To this end, we must define a `std::error_category` that represents our `libfoo_error` type:
[source,c++]
----
std::error_category const & libfoo_error_category()
{
struct category: std::error_category
{
char const * name() const noexcept override
{
return "libfoo";
}
std::string message(int code) const override
{
switch( libfoo_error(code) )
{
case libfoo_error::e1: return "e1";
case libfoo_error::e2: return "e2";
case libfoo_error::e3: return "e3";
default: return "error";
}
}
};
static category c;
return c;
}
----
We also need to inform the standard library that `libfoo_error` is compatible with `std::error_code`, and provide a factory function which can be used to make `std::error_code` objects out of `libfoo_error` values:
[source,c++]
----
namespace std
{
template <>
struct is_error_code_enum: std::true_type
{
};
}
std::error_code make_error_code(libfoo_error e)
{
return std::error_code(int(e), libfoo_error_category());
}
----
With this in place, if we receive a `std::error_code`, we can easily check if it represents some of the `libfoo_error` values we're interested in:
[source,c++]
----
std::error_code f();
....
auto ec = f();
if( ec == libfoo_error::e1 || ec == libfoo_error::e2 )
{
// We got either a libfoo_error::e1 or a libfoo_error::e2
}
----
This works because the standard library detects that `std::is_error_code_enum::value` is `true`, and then uses `make_error_code` to create a `std::error_code` object it actually uses to compare to `ec`.
So far so good, but remember, the standard library defines another type also, `std::error_condition`. The first confusing thing is that in terms of its physical representation, `std::error_condition` is identical to `std::error_code`; that is, it is also like a pair of `std::error_category` reference and an `int`. Why do we need two different types which use identical physical representation?
The key to answering this question is to understand that `std::error_code` objects are designed to be returned from functions to indicate failures. In contrast, `std::error_condition` objects are [underline]#never# supposed to be communicated; their purpose is to interpret the `std::error_code` values being communicated. The idea is that in a given program there may be multiple different "physical" (maybe platform-specific) `std::error_code` values which all indicate the same "logical" `std::error_condition`.
This leads us to the second confusing thing about `std::error_condition`: it uses the same `std::error_category` type, but for a completely different purpose: to specify what `std::error_code` values are equivalent to what `std::error_condition` values.
Let's say that in addition to `libfoo`, our program uses another library, `libbar`, which communicates failures in terms of `std::error_code` with a different error category. Perhaps `libbar_error` looks like this:
[source,c++]
----
enum class libbar_error
{
e1 = 1,
e2,
e3,
e4
};
// Boilerplate omitted:
// - libbar_error_category()
// - specialization of std::is_error_code_enum
// - make_error_code factory function for libbar_error.
----
We can now use `std::error_condition` to define the _logical_ error conditions represented by the `std::error_code` values communicated by `libfoo` and `libbar`:
[source,c++]
----
enum class my_error_condition <1>
{
c1 = 1,
c2
};
std::error_category const & libfoo_error_category() <2>
{
struct category: std::error_category
{
char const * name() const noexcept override
{
return "my_error_condition";
}
std::string message(int cond) const override
{
switch( my_error_condition(code) )
{
case my_error_condition::c1: return "c1";
case my_error_condition::c2: return "c2";
default: return "error";
}
}
bool equivalent(std::error_code const & code, int cond) const noexcept
{
switch( my_error_condition(cond) )
{
case my_error_condition::c1: <3>
return
code == libfoo_error::e1 ||
code == libbar_error::e3 ||
code == libbar_error::e4;
case my_error_condition::c2: <4>
return
code == libfoo_error::e2 ||
code == libbar_error::e1 ||
code == libbar_error::e2;
default:
return false;
}
}
};
static category c;
return c;
}
namespace std
{
template <> <5>
class is_error_condition_enum: std::true_type
{
};
}
std::error_condition make_error_condition(my_error_condition e) <6>
{
return std::error_condition(int(e), my_error_condition_error_category());
}
----
<1> Enumeration of the two logical error conditions, `c1` and `c2`.
<2> Define the `std::error_category` for `std::error_condition` objects that represent a `my_error_condition`.
<3> Here we specify that any of `libfoo:error::e1`, `libbar_error::e3` and `libbar_error::e4` are logically equivalent to `my_error_condition::c1`, and that...
<4> ...any of `libfoo:error::e2`, `libbar_error::e1` and `libbar_error::e2` are logically equivalent to `my_error_condition::c2`.
<5> This specialization tells the standard library that the `my_error_condition` enum is designed to be used with `std::error_condition`.
<6> The factory function to make `std::error_condition` objects out of `my_error_condition` values.
Phew!
Now, if we have a `std::error_code` object `ec`, we can easily check if it is equivalent to `my_error_condition::c1` like so:
[source,c++]
----
if( ec == my_error_condition::c1 )
{
// We have a c1 in our hands
}
----
Again, remember that beyond defining the `std::error_category` for `std::error_condition` objects initialized with a `my_error_condition` value, we don't need to interact with the actual `std::error_condition` instances: they're created when needed to compare to a `std::error_code`, and that's pretty much all they're good for.
==== Support in LEAF
The following support for `std::error_code` and `std::error_condition` is available:
* The <> template can be used as an argument to a LEAF error handler, so it can be considered based on the value of a communicated `std::error_code`.
+
NOTE: See <> for examples.
+
* The <> type can be converted to a `std::error_code`; see <>. The returned object encodes the state of the `error_id` without any loss of information. This is useful if an `error_id` needs to be communicated through interfaces that support `std::error_code` but do not use LEAF.
* The `error_id` type can be implicitly initialized with a `std::error_code`. If the `std::error_code` was created using `to_error_code`, the original `error_id` state is restored. Otherwise, the `std::error_code` is <> so it can be used by LEAF error handlers, while the `error_id` itself is initialized by <>.
* The `leaf::result` type can be implicitly initialized with an `error_id`, which means that it can be implicitly initialized with a `std::error_code`.
'''
[[tutorial-boost_exception_integration]]
=== Boost Exception Integration
Instead of the https://www.boost.org/doc/libs/release/libs/exception/doc/get_error_info.html[`boost::get_error_info`] API defined by Boost Exception, it is possible to use LEAF error handlers directly. Consider the following use of `boost::get_error_info`:
[source,c++]
----
typedef boost::error_info my_info;
void f(); // Throws using boost::throw_exception
void g()
{
try
{
f();
},
catch( boost::exception & e )
{
if( int const * x = boost::get_error_info(e) )
std::cerr << "Got my_info with value = " << *x;
} );
}
----
We can rewrite `g` to access `my_info` using LEAF:
[source,c++]
----
#include
void g()
{
leaf::try_catch(
[]
{
f();
},
[]( my_info x )
{
std::cerr << "Got my_info with value = " << x.value();
} );
}
----
[.text-right]
<>
Taking `my_info` means that the handler will only be selected if the caught exception object carries `my_info` (which LEAF accesses via `boost::get_error_info`).
The use of <> is also supported:
[source,c++]
----
void g()
{
leaf::try_catch(
[]
{
f();
},
[]( leaf::match_value )
{
std::cerr << "Got my_info with value = 42";
} );
}
----
Above, the handler will be selected if the caught exception object carries `my_info` with `.value()` equal to 42.
[[examples]]
== Examples
See https://github.com/boostorg/leaf/tree/master/examples[github].
[[synopsis]]
== Synopsis
This section lists each public header file in LEAF, documenting the definitions it provides.
LEAF headers are designed to minimize coupling:
* Headers needed to report or forward but not handle errors are lighter than headers providing error-handling functionality.
* Headers that provide exception handling or throwing functionality are separate from headers that provide error-handling or reporting but do not use exceptions.
A standalone single-header option is available; please `#include `.
'''
[[synopsis-reporting]]
=== Error Reporting
[[error.hpp]]
==== `error.hpp`
====
.#include
[source,c++]
----
namespace boost { namespace leaf {
class error_id
{
public:
error_id() noexcept;
template
error_id( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept;
error_id( std::error_code const & ec ) noexcept;
int value() const noexcept;
explicit operator bool() const noexcept;
std::error_code to_error_code() const noexept;
friend bool operator==( error_id a, error_id b ) noexcept;
friend bool operator!=( error_id a, error_id b ) noexcept;
friend bool operator<( error_id a, error_id b ) noexcept;
template
error_id load( Item && ... item ) const noexcept;
friend std::ostream & operator<<( std::ostream & os, error_id x );
};
bool is_error_id( std::error_code const & ec ) noexcept;
template
error_id new_error( Item && ... item ) noexcept;
error_id current_error() noexcept;
//////////////////////////////////////////
class polymorphic_context
{
protected:
polymorphic_context() noexcept = default;
~polymorphic_context() noexcept = default;
public:
virtual void activate() noexcept = 0;
virtual void deactivate() noexcept = 0;
virtual bool is_active() const noexcept = 0;
virtual void propagate() noexcept = 0;
virtual void print( std::ostream & ) const = 0;
};
//////////////////////////////////////////
template
class context_activator
{
context_activator( context_activator const & ) = delete;
context_activator & operator=( context_activator const & ) = delete;
public:
explicit context_activator( Ctx & ctx ) noexcept;
context_activator( context_activator && ) noexcept;
~context_activator() noexcept;
};
template
context_activator activate_context( Ctx & ctx ) noexcept;
template
struct is_result_type: std::false_type
{
};
template
struct is_result_type: is_result_type
{
};
} }
#define BOOST_LEAF_ASSIGN(v, r)\
auto && <> = r;\
if( !<> )\
return <>.error();\
v = std::forward>)>(<>).value()
#define BOOST_LEAF_AUTO(v, r)\
BOOST_LEAF_ASSIGN(auto v, r)
#define BOOST_LEAF_CHECK(r)\
auto && <> = r;\
if( <> )\
;\
else\
return <>.error()
#define BOOST_LEAF_NEW_ERROR <> ::boost::leaf::new_error
----
[.text-right]
Reference: <> | <> | <> | <> | <> | <> | <> | <> | <> | <> | <> | <>
====
[[common.hpp]]
==== `common.hpp`
====
.#include
[source,c++]
----
namespace boost { namespace leaf {
struct e_api_function { char const * value; };
struct e_file_name { std::string value; };
struct e_type_info_name { char const * value; };
struct e_at_line { int value; };
struct e_errno
{
int value;
friend std::ostream & operator<<( std::ostream &, e_errno const & );
};
namespace windows
{
struct e_LastError
{
unsigned value;
friend std::ostream & operator<<( std::ostream &, e_LastError const & );
};
}
} }
----
[.text-right]
Reference: <> | <> | <> | <