Abstract
Boost LEAF is a lightweight error handling library for C++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.
Tutorial | Synopsis | Whitepaper | Benchmark |
Reference: Functions | Types | Predicates | Traits | Macros |
LEAF is designed with a strong bias towards the common use case where callers of functions which may fail check for success and forward errors up the call 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
-
cpplang on Slack (use the
#boost
channel) -
Report an issue on GitHub
Portability
LEAF requires only C++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 Configuration Macros.
Distribution
Copyright © 2018-2021 Emil Dotchevski. Distributed under the Boost Software License, Version 1.0.
There are three distribution channels:
LEAF does not depend on Boost or other libraries. |
Tutorial
What is a failure? It is simply the inability of a function to return a valid result, instead producing an error object describing the reason for the failure.
A typical design is to return a variant type, e.g. result<T, E>
. Internally, such variant types must store a discriminant (in this case a boolean) to indicate whether the object holds a T
or an E
.
The design of LEAF is informed by the observation that the immediate caller must have access to the discriminant in order to determine the availability of a valid T
, but otherwise it rarely needs to access the E
. The error object is only needed once an error handling scope is reached.
Therefore what would have been a result<T, E>
becomes result<T>
, which stores the discriminant and (optionally) a T
, while the E
is communicated directly to the error handling scope where it is needed.
The benefit of this decomposition is that result<T>
becomes extremely lightweight, as it is not coupled with error types; further, error objects are communicated in O(1) time (independent of the call stack depth). Even very large objects are handled efficiently without dynamic memory allocation.
Reporting Errors
A function that reports an error is pretty straight-forward:
enum class err1 { e1, e2, e3 };
leaf::result<T> f()
{
....
if( error_detected )
return leaf::new_error( err1::e1 ); // Pass an error object of any type
// Produce and return a T.
}
Checking for Errors
Checking for errors communicated by a leaf::result<T>
works as expected:
leaf::result<U> g()
{
leaf::result<T> r = f();
if( !r )
return r.error();
T const & v = r.value();
// Use v to produce a valid U
}
The boilerplate if
statement can be avoided using BOOST_LEAF_AUTO
:
leaf::result<U> g()
{
BOOST_LEAF_AUTO(v, f()); // Bail out on error
// Use v to produce a valid U
}
Error Handling
Error handling scopes must use a special syntax to indicate that they need to access error objects. The following excerpt attempts several operations and handles errors of type err1
:
leaf::result<U> r = leaf::try_handle_some(
[]() -> leaf::result<U>
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1, v2);
},
[]( err1 e ) -> leaf::result<U>
{
if( e == err1::e1 )
.... // Handle err1::e1
else
.... // Handle any other err1 value
} );
The first lambda passed to try_handle_some
is executed first; it attempts to produce a result<U>
, but it may fail (we presume that f1
and f2
return leaf::result<T>
, and g
takes two arguments of type T
and returns a leaf::result<U>
).
The second lambda is an error handler: it will be called iff the first lambda fails and an error object of type err1
was communicated to LEAF. That object is stored on the stack, local to the try_handle_some
function (LEAF knows to allocate this storage because we gave it an error handler that takes an err1
). Error handlers passed to leaf::try_handle_some
can return a valid leaf::result<U>
but are allowed to fail.
It is possible for an error handler to specify that it can only deal with a particular value of a given error type:
leaf::result<U> r = leaf::try_handle_some(
[]() -> leaf::result<U>
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1. v2);
},
[]( leaf::match<err1, err1::e1> ) -> leaf::result<U>
{
// Handle err::e1
},
[]( err1 e ) -> leaf::result<U>
{
// Handle any other err1 value
} );
LEAF considers the provided error handlers in order, and calls the first one for which it can supply arguments, based on the error objects currently being communicated. Above:
-
The first error handler uses the predicate
leaf::match
to specify that it should only be considered if an error object of typeerr1
is available, and its value iserr1::e1
. -
Otherwise the second error handler will be called if an error object of type
err1
is available, regardless of its value. -
Otherwise
leaf::try_handle_some
fails.
If we want to ensure that all possible failures are handled, we use leaf::try_handle_all
instead of leaf::try_handle_some
:
U r = leaf::try_handle_all(
[]() -> leaf::result<U>
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1. v2);
},
[]( leaf::match<err1, err1::e1> ) -> U
{
// Handle err::e1
},
[]( err1 e ) -> U
{
// Handle any other err1 value
},
[]() -> U
{
// Handle any other failure
} );
The leaf::try_handle_all
function enforces at compile time that at least one of the supplied error handlers takes no arguments (and therefore is able to handle any failure). In addition, all error handlers are forced to return a valid U
, rather than a leaf::result<U>
, so that leaf::try_handle_all
is guaranteed to succeed, always.
Working with Different Error Types
It is of course possible to provide different handlers for different error types:
enum class err1 { e1, e2, e3 };
enum class err2 { e1, e2 };
....
leaf::result<U> r = leaf::try_handle_some(
[]() -> leaf::result<U>
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1, v2);
},
[]( err1 e ) -> leaf::result<U>
{
// Handle errors of type `err1`.
},
[]( err2 e ) -> leaf::result<U>
{
// Handle errors of type `err2`.
} );
In this case, because we have supplied handlers for err1
and for err2
, try_handle_some
knows to allocate storage on the stack for error objects of both types.
Working with Multiple Error Objects
It is possible for an error handler to require more than one error object:
enum class err1 { e1, e2, e3 };
enum class err2 { e1, e2 };
....
leaf::result<U> r = leaf::try_handle_some(
[]() -> leaf::result<U>
{
BOOST_LEAF_AUTO(v1, f1());
BOOST_LEAF_AUTO(v2, f2());
return g(v1, v2);
},
[]( err1 e1, err2 e2 ) -> leaf::result<U>
{
// Handle failures which communicate both an err1 and an err2 object.
} );
Naturally, leaf::new_error
can be invoked with multiple error objects:
leaf::result<T> f()
{
....
if( error_detected )
return leaf::new_error(err1::e1, err2::e2);
// Produce and return a T.
}
As well, leaf::on_error
can be used to automatically associate additional error objects with any failure that is "in flight":
enum class io_error { open_error, read_error, write_error };
enum class parse_error { bad_syntax, bad_range };
leaf::result<int> parse_line( FILE * f );
struct e_line { int value; };
leaf::result<void> 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
}
}
Presumably, parse_line
could fail with an io_error
or with a parse_error
, but process_file
does not handle errors, so it remains neutral to failures, except to attach the current_line
if something goes wrong. The object returned by on_error
holds a copy of the current_line
wrapped in struct e_line
. If parse_line
succeeds, the e_line
object is simply discarded; but if it fails, the e_line
object will be automatically attached to the failure.
Such failures can then be handled like so:
leaf::result<void> r = leaf::try_handle_some(
[]() -> leaf::result<void>
{
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;
} );
Remember, error handlers are considered in order, so the last one will be called if we get an io_error
but no e_line
was communicated to LEAF. Alternatively, we can provide a single io_error
handler that takes current_line
as a pointer-to-const:
leaf::result<void> r = leaf::try_handle_some(
[]() -> leaf::result<void>
{
BOOST_LEAF_CHECK( process_file(f) );
},
[]( parse_error e, e_line current_line )
{
std::cerr << "Parse error at line " << current_line.value << std::endl;
},
[]( io_error e, e_line const * current_line )
{
std::cerr << "Parse error";
if( current_line )
std::cerr << " at line " << current_line->value;
std::cerr << std::endl;
} );
In essence, now the e_line
argument is optional, LEAF will provide it if it is available, otherwise pass a null pointer.
Exception Handling
What happens if an operation throws an exception? Not to worry, both leaf::try_handle_some
and leaf::try_handle_all
catch exceptions and are able to pass them to any compatible error handler:
leaf::result<void> r = leaf::try_handle_some(
[]() -> leaf::result<void>
{
BOOST_LEAF_CHECK( process_file(f) );
},
[]( std::bad_alloc const & )
{
std::cerr << "Out of memory!" << std::endl;
},
[]( parse_error e, e_line l )
{
std::cerr << "Parse error at line " << l.value << std::endl;
},
[]( io_error e, e_line const * l )
{
std::cerr << "Parse error";
if( l )
std::cerr << " at line " << l.value;
std::cerr << std::endl;
} );
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
:
leaf::try_catch(
[]
{
process_file(f);
},
[]( std::bad_alloc const & )
{
std::cerr << "Out of memory!" << std::endl;
},
[]( parse_error e, e_line l )
{
std::cerr << "Parse error at line " << l.value << std::endl;
},
[]( io_error e, e_line const * l )
{
std::cerr << "Parse error";
if( l )
std::cerr << " at line " << l.value;
std::cerr << std::endl;
} );
Remarkably, we did not have to change the error handlers! But how does this work? What kind of exceptions does process_file
throw?
LEAF enables a novel technique of exception handling, which does not use exception type hierarchies 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:
enum class err1 { e1, e2, e3 };
enum class err2 { e1, e2 };
....
leaf::result<T> f()
{
....
if( error_detected )
return leaf::new_error(err1::e1, err2::e2);
// Produce and return a T.
}
When using exception handling this becomes:
enum class err1 { e1, e2, e3 };
enum class err2 { e1, e2 };
T f()
{
if( error_detected )
throw leaf::exception(err1::e1, err2::e2);
// Produce and return a T.
}
The leaf::exception
function handles the passed error objects just like leaf::new_error
does, and then returns an object of a type that derives from std::exception
(which the caller throws). Using this technique, the exception type is not important: leaf::try_catch
catches all exceptions, then goes through the usual LEAF error handler selection machinery.
If instead we want to use the legacy convention of throwing different types to indicate different failures, we simply pass an exception object (that is, an object of a type that derives from std::exception
) as the first argument to leaf::exception
:
throw leaf::exception(std::runtime_error("Error!"), err1::e1, err2::e2);
In this case the returned object will be of type that derives from std::runtime_error
, rather than from std::exception
.
Finally, leaf::on_error
"just works" as well. Here is our process_file
function rewritten to throw on error, rather than return a leaf::result
:
enum class io_error { open_error, read_error, write_error };
enum class parse_error { bad_syntax, bad_range };
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
}
}
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 C++ in general because the community is fractured on the issue of exception handling. Regardless of any arguments, the reality is that C++ programs need to be able 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:
lib1::result<int, lib1::error_code> foo();
lib2::result<int, lib2::error_code> bar();
int g( int a, int b );
leaf::result<int> 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() );
}
Later we simply call leaf::try_handle_some
passing an error handler for each type:
leaf::result<int> r = leaf::try_handle_some(
[]() -> leaf::result<int>
{
return f();
},
[]( lib1::error_code ec ) -> leaf::result<int>
{
// Handle lib1::error_code
},
[]( lib2::error_code ec ) -> leaf::result<int>
{
// Handle lib2::error_code
} );
}
A possible complication is that we might not have the option to return leaf::result<int>
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:
void register_callback( std::function<lib3::result<int>()> 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:
namespace boost { namespace leaf {
template <class T>
struct is_result_type<lib3::result<T>>: std::true_type;
} }
With this in place, f
works as before, even though lib3::result
isn’t capable of transporting lib1
errors or lib2
errors:
lib1::result<int, lib1::error_type> foo();
lib2::result<int, lib2::error_type> bar();
int g( int a, int b );
lib3::result<int> 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() );
}
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
):
lib3::result<int> r = leaf::try_handle_some(
[]() -> lib3::result<int>
{
return f();
},
[]( lib1::error_code ec ) -> lib3::result<int>
{
// Handle lib1::error_code
},
[]( lib2::error_code ec ) -> lib3::result<int>
{
// Handle lib2::error_code
} );
}
Error Communication Model
noexcept
API
The following figure illustrates how error objects are transported when using LEAF without exception handling:
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<T>
object r
. That object takes the path shown by dashed arrows, as each error neutral function, unable to handle the failure, forwards it to its immediate caller in the returned value — until an error handling scope is reached.
When the destructor of the load
object in f3
executes, it detects that new_error
was invoked after its initialization, loads the cached objects of types E1
and E3
in the first active context
object that provides static storage for them, found in any calling scope (in this case f1
), and associates them with the last generated error_id
(solid arrow).
When the error handling scope f1
is reached, it probes ctx
for any 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:
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
.
Interoperability
Ideally, when an error is detected, a program using LEAF would always call new_error
, ensuring that each encountered failure is definitely assigned a unique error_id
, which then is reliably delivered, by an exception or by a result<T>
object, to the appropriate error handling scope.
Alas, this is not always possible.
For example, the error may need to be communicated through uncooperative 3rd-party interfaces. To facilitate this transmission, a error ID may be encoded in a std::error_code
. As long as a 3rd-party interface is able to transport a std::error_code
, it should be compatible with LEAF.
Further, it is sometimes necessary to communicate errors through an interface that does not even use std::error_code
. An example of this is when an external lower-level library throws an exception, which is unlikely to be able to carry an error_id
.
To support this tricky use case, LEAF provides the function current_error
, which returns the error ID returned by the most recent call (from this thread) to new_error
. One possible approach to solving the problem is to use the following logic (implemented by the error_monitor
type):
-
Before calling the uncooperative API, call
current_error
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 newerror_id
; -
else, associate the error objects with the
error_id
value returned by the second call tocurrent_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 Using error_monitor
to Report Arbitrary Errors from C-callbacks.
To avoid ambiguities, whenever possible, use the exception function template when throwing exceptions to ensure that the exception object transports a unique error_id ; better yet, use the BOOST_LEAF_THROW_EXCEPTION macro, which in addition will capture __FILE__ and __LINE__ .
|
Loading of Error Objects
To load an error object is to move it into an active context
, usually local to a try_handle_some
, a try_handle_all
or a try_catch
scope in the calling thread, where it becomes uniquely associated with a specific error_id
— or discarded if storage is not available.
Various LEAF functions take a list of 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 new_error
:
return leaf::new_error(ec, e_input_name{n1}, e_output_name{n2});
Alternatively, error objects may be loaded using a result<T>
that is already communicating an error. This way they become associated with that error, rather than with a new error:
leaf::result<int> f() noexcept;
leaf::result<void> g( char const * fn ) noexcept
{
if( leaf::result<int> r = f() )
{ (1)
....;
return { };
}
else
{
return r.load( e_file_name{fn} ); (2)
}
}
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 toload
is an excellent way to achieve this behavior:struct info { .... }; info compute_info() noexcept; leaf::result<void> operation( char const * file_name ) noexcept { if( leaf::result<int> r = try_something() ) { (1) .... return { }; } else { return r.load( (2) [&] { return compute_info(); } ); } }
1 Success! Use r.value()
.2 try_something
has failed;compute_info
will only be called if an error handler exists which takes ainfo
argument. -
If we pass a function that takes a single argument of type
E &
, LEAF calls the function with the object of typeE
currently loaded in an activecontext
, 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:struct e_relevant_file_names { std::vector<std::string> value; }; leaf::result<void> operation( char const * file_name ) noexcept { if( leaf::result<int> r = try_something() ) { (1) .... return { }; } else { return r.load( (2) [&](e_relevant_file_names & e) { e.value.push_back(file_name); } ); } }
1 Success! Use r.value()
.2 try_something
has failed — addfile_name
to thee_relevant_file_names
object, associated with theerror_id
communicated inr
. Note, however, that the passed function will only be called iff in the call stack there are error handlers that take ane_relevant_file_names
object.
Using on_error
It is not typical for an error reporting function to be able to supply all of the data needed by a suitable error handling function in order to recover from the failure. For example, a function that reports FILE
failures may not have access to the file name, yet an error handling function needs it in order to print a useful error message.
Of course the file name is typically readily available in the call stack leading to the failed FILE
operation. Below, while parse_info
can’t report the file name, parse_file
can and does:
leaf::result<info> parse_info( FILE * f ) noexcept; (1)
leaf::result<info> 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 );
}
1 | parse_info parses f , communicating errors using result<info> . |
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. |
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 e_errno
to it, because at that time it hasn’t been set (yet). Instead, we’d pass a function that returns it:
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 argument type that can be passed to on_error
is a function that takes a single mutable error object reference. In this case, on_error
uses it similarly to how such functions are used by load
; see Loading of Error Objects.
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 handler selection procedure is able to also take into account the value of the available error objects.
Consider this error code enum:
enum class my_error
{
e1=1,
e2,
e3
};
We could handle my_error
errors like so:
return leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( 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 match
predicate to organize the different cases in different error handlers. The following is equivalent:
return leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match<my_error, my_error::e1> m )
{ (1)
assert(m.matched == my_error::e1);
....;
},
[]( leaf::match<my_error, my_error::e2, my_error::e3> m )
{ (2)
assert(m.matched == my_error::e2 || m.matched == my_error::e3);
....;
},
[]( my_error e )
{ (3)
....;
} );
1 | We’ve got a my_error object that compares equal to e1 . |
2 | We`ve got a my_error object that compares equal to either e2 or e3 . |
3 | Handle bad my_error values. |
The first argument to the match
template generally specifies the type E
of the error object e
that must be available for the error handler to be considered at all. Typically, the rest of the arguments are values. The error handler is dropped if e
does not compare equal to any of them.
In particular, match
works great with std::error_code
. The following handler is designed to handle ENOENT
errors:
[]( leaf::match<std::error_code, std::errc::no_such_file_or_directory> )
{
}
This, however, requires C++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 C++11 does not allow auto
template arguments. LEAF provides the following workaround, compatible with C++11:
[]( leaf::match<leaf::condition<std::errc>, 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 C++17 or newer):
[]( std::error_code, leaf::category<std::errc>> )
{
}
See match for more examples.
|
The following predicates are available:
-
match
: as described above. -
match_value
: wherematch<E, V…>
compares the objecte
of typeE
with the valuesV…
,match_value<E, V…>
comparee.value
with the valuesV…
. -
match_member
: similar tomatch_value
, but takes a pointer to the data member to compare; that is,match_member<&E::value, V…>
is equvialent tomatch_value<E, V…>
. Note, however, thatmatch_member
requires C++17 or newer, whilematch_value
does not. -
catch_<Ex…>
: Similar tomatch
, but checks whether the caughtstd::exception
object can bedynamic_cast
to any of theEx
types. -
if_not
is a special predicate that takes any other predicatePred
and requires that an error object of typeE
is available and thatPred
evaluates tofalse
. For example,if_not<match<E, V…>>
requires that an objecte
of typeE
is available, and that it does not compare equal to any of the specifiedV…
.
Finally, the predicate system is easily extensible, see Predicates.
Binding Error Handlers in a std::tuple
Consider this snippet:
leaf::try_handle_all(
[&]
{
return f(); // returns leaf::result<T>
},
[](my_error_enum x)
{
...
},
[](read_file_error_enum y, e_file_name const & fn)
{
...
},
[]
{
...
});
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
:
leaf::try_handle_all(
[&]
{
return g(); // returns leaf::result<T>
},
[](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
:
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:
leaf::try_handle_all(
[&]
{
// Operations which may fail (1)
},
error_handlers );
leaf::try_handle_all(
[&]
{
// Different operations which may fail (2)
},
error_handlers ); (3)
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.
Transporting Error Objects Between Threads
Error objects are stored on the stack in an instance of the context
class template in the scope of e.g. try_handle_some
, try_handle_all
or try_catch
functions. When using concurrency, we need a mechanism to collect error objects in one thread, then use them to handle errors in another thread.
LEAF offers two interfaces for this purpose, one using result<T>
, and another designed for programs that use exception handling.
Using result<T>
Let’s assume we have a task
that we want to launch asynchronously, which produces a task_result
but could also fail:
leaf::result<task_result> task();
Because the task will run asynchronously, in case of a failure we need it to capture the relevant 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 tutorial):
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 context
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
:
std::shared_ptr<leaf::polymorphic_context> 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<E1, E2, E3>
, 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:
std::future<leaf::result<task_result>> launch_task() noexcept
{
return std::async(
std::launch::async,
[&]
{
std::shared_ptr<leaf::polymorphic_context> ctx = leaf::make_shared_context(error_handlers);
return leaf::capture(ctx, &task);
} );
}
That’s it! Later when we get
the std::future
, we can process the returned result<task_result>
in a call to try_handle_some
, using the error_handlers
tuple we created earlier:
//std::future<leaf::result<task_result>> fut;
fut.wait();
return leaf::try_handle_some(
[&]() -> leaf::result<void>
{
BOOST_LEAF_AUTO(r, fut.get());
//Success!
return { }
},
error_handlers );
The reason this works is that in case the leaf::result<T>
communicates a failure, it is able to hold a shared_ptr<polymorphic_context>
object. That is why earlier instead of calling task()
directly, we called leaf::capture
: it calls the passed function and, in case that fails, it stores the shared_ptr<polymorphic_context>
we created in the returned result<T>
, which now doesn’t just communicate the fact that an error has occurred, but also holds the context
object that try_handle_some
needs in order to supply a suitable handler with arguments.
Follow this link to see a complete example program: capture_in_result.cpp. |
Using Exception Handling
Let’s assume we have an asynchronous task
which produces a task_result
but could also throw:
task_result task();
Just like we saw in Using result<T>
, first we will bind our error handlers in a std::tuple
:
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<T>
:
std::future<task_result> launch_task()
{
return std::async(
std::launch::async,
[&]
{
std::shared_ptr<leaf::polymorphic_context> ctx = leaf::make_shared_context(&handle_error);
return leaf::capture(ctx, &task);
} );
}
That’s it! Later when we get
the std::future
, we can process the returned task_result
in a call to try_catch
, using the error_handlers
we saved earlier, as if it was generated locally:
//std::future<task_result> fut;
fut.wait();
return leaf::try_catch(
[&]
{
task_result r = fut.get(); // Throws on error
//Success!
},
error_handlers );
This works similarly to using result<T>
, except that the std::shared_ptr<polymorphic_context>
is transported in an exception object (of unspecified type which try_catch
recognizes and then automatically unwraps the original exception).
Follow this link to see a complete example program: capture_in_exception.cpp. |
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:
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:
....
[](leaf::match<error_code, size_error, read_error, eof_error>, leaf::e_file_name const & fn)
{
std::cerr << "Failed to access " << fn.value << std::endl;
},
....
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:
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:
[](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:
....
struct input_error { };
struct read_error { };
struct size_error { };
struct eof_error { };
....
With this in place, we could define a function file_read
:
leaf::result<void> 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 { };
}
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:
leaf::result<void> 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 { };
}
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::exception
instead of leaf::new_error
:
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{});
}
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.
|
Now we can write a future-proof handler for any input_error
:
....
[](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.
Converting Exceptions to result<T>
It is sometimes necessary to catch exceptions thrown by a lower-level library function, and report the error through different means, to a higher-level library which may not use exception handling.
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 loaded into a context . 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
:
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<int>
for error handling:
leaf::result<int> compute_answer() noexcept
{
return leaf::exception_to_result<error_a, error_b>(
[]
{
return compute_answer_throws();
} );
}
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 loaded, and in the end the exception is converted to a result<T>
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:
leaf::result<void> print_answer() noexcept
{
BOOST_LEAF_AUTO(answer, compute_answer());
std::cout << "Answer: " << answer << std::endl;
return { };
}
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.
leaf::try_handle_all(
[]() -> leaf::result<void>
{
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;
} );
The complete program illustrating this technique is available here. |
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 C++ types.
LEAF makes this easy. As an example, we’ll write a program that uses Lua and reports a failure from a C++ function registered as a C callback, called from a Lua program. The failure will be propagated from C++, through the Lua interpreter (written in C), back to the C++ function which called it.
C/C++ functions designed to be invoked from a Lua program must use the following signature:
int do_work( lua_State * L ) ;
Arguments are passed on the Lua stack (which is accessible through L
). Results too are pushed onto the Lua stack.
First, let’s initialize the Lua interpreter and register a function, do_work
, as a C callback available for Lua programs to call:
std::shared_ptr<lua_State> init_lua_state() noexcept
{
std::shared_ptr<lua_State> L(lua_open(), &lua_close); (1)
lua_register(&*L, "do_work", &do_work); (2)
luaL_dostring(&*L, "\ (3)
\n function call_do_work()\
\n return do_work()\
\n end");
return L;
}
1 | Create a new lua_State . We’ll use std::shared_ptr for automatic cleanup. |
2 | Register the do_work C++ function as a C callback, under the global name do_work . With this, calls from Lua programs to do_work will land in the do_work C++ function. |
3 | Pass some Lua code as a C string literal to Lua. This creates a global Lua function called call_do_work , which we will later ask Lua to execute. |
Next, let’s define our enum
used to communicate do_work
failures:
enum do_work_error_code
{
ec1=1,
ec2
};
We’re now ready to define the do_work
callback function:
int do_work( lua_State * L ) noexcept
{
bool success = rand() % 2; (1)
if( success )
{
lua_pushnumber(L, 42); (2)
return 1;
}
else
{
(void) leaf::new_error(ec1); (3)
return luaL_error(L, "do_work_error"); (4)
}
}
1 | "Sometimes" do_work fails. |
2 | In case of success, push the result on the Lua stack, return back to Lua. |
3 | Generate a new error_id and associate a do_work_error_code with it. Normally, we’d return this in a leaf::result<T> , but the do_work function signature (required by Lua) does not permit this. |
4 | Tell the Lua interpreter to abort the Lua program. |
Now we’ll write the function that calls the Lua interpreter to execute the Lua function call_do_work
, which in turn calls do_work
. We’ll return result<int>
, so that our caller can get the answer in case of success, or an error:
leaf::result<int> call_lua( lua_State * L )
{
lua_getfield(L, LUA_GLOBALSINDEX, "call_do_work");
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;
}
}
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:
int main() noexcept
{
std::shared_ptr<lua_State> L=init_lua_state();
for( int i=0; i!=10; ++i )
{
leaf::try_handle_all(
[&]() -> leaf::result<void>
{
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;
} );
}
1 | If the call to call_lua succeeded, just print the answer. |
2 | Handle do_work failures. |
3 | Handle all other lua_pcall failures. |
Follow this link to see the complete program: lua_callback_result.cpp. |
When using Lua with C++, we need to protect the Lua interpreter from exceptions that may be thrown from C++ functions installed as lua_CFunction callbacks. Here is the program from this section rewritten to use a C++ exception to safely communicate errors out of the do_work function: lua_callback_eh.cpp.
|
Diagnostic Information
LEAF is able to automatically generate diagnostic messages that include information about all error objects available to error handlers:
enum class error_code
{
read_error,
write_error
};
....
leaf::try_handle_all(
[]() -> leaf::result<void> (1)
{
...
return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } );
},
[]( leaf::match<error_code, error_code::read_error> ) (2)
{
std::cerr << "Read error!" << std::endl;
},
[]( leaf::verbose_diagnostic_info const & info ) (3)
{
std::cerr << "Unrecognized error detected, cryptic diagnostic information follows.\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 | The "catch all" error handler is required by try_handle_all . It will be called if LEAF is unable to use another error handler. |
The verbose_diagnostic_info
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, cryptic diagnostic information follows. leaf::verbose_diagnostic_info for Error ID = 1: [with Name = error_code]: 1 Unhandled error objects: [with Name = boost::leaf::e_file_name]: file.txt
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.:
struct e_errno
{
int value;
friend std::ostream & operator<<( std::ostream & os, e_errno const & e )
{
return os << "errno = " << e.value << ", \"" << strerror(e.value) << '"';
}
};
The e_errno
type above is designed to hold errno
values. The defined operator<<
overload will automatically include the output from strerror
when e_errno
values are printed (LEAF defines e_errno
in <boost/leaf/common.hpp>
, together with other commonly-used error types).
Using verbose_diagnostic_info
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 verbose_diagnostic_info
argument, before such objects are discarded, they are printed and appended to a std::string
(this is the case with e_file_name
in our example above). Such objects appear under Unhandled error objects
in the output from verbose_diagnostic_info
.
If handling verbose_diagnostic_info
is considered too costly, use diagnostic_info
instead:
leaf::try_handle_all(
[]() -> leaf::result<void>
{
...
return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } );
},
[]( leaf::match<error_code, error_code::read_error> )
{
std::cerr << "Read error!" << std::endl;
},
[]( leaf::diagnostic_info const & info )
{
std::cerr << "Unrecognized error detected, cryptic diagnostic information follows.\n" << info;
} );
In this case, the output may look like this:
Unrecognized error detected, cryptic diagnostic information follows. leaf::diagnostic_info for Error ID = 1: [with Name = error_code]: 1 Detected 1 attempt to communicate an unexpected error object of type [with Name = boost::leaf::e_file_name]
Notice how the diagnostic information for e_file_name
changed: LEAF no longer prints it before discarding it, and so diagnostic_info
can only inform about the type of the discarded object, but not its value.
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.
|
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
reference. Conceptually, a std::error_code
is like a pair<std::error_category const &, int>
.
Let’s say we have this enum
:
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:
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:
namespace std
{
template <>
struct is_error_code_enum<libfoo_error>: 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:
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<libfoo_error>::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 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:
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
:
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<my_error_condition>: 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:
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 match
predicate can be used as an argument to a LEAF error handler to match a std::error_code
with a given error condition. For example, to handle my_error_condition::c1
(see above), we could use:
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match<std::error_code, my_error_condition::c1> m )
{
assert(m.matched == my_error_condition::c1);
....
} );
See match
for more examples.
Boost Exception Integration
Instead of the 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
:
typedef boost::error_info<struct my_info_, int> 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<my_info>(e) )
std::cerr << "Got my_info with value = " << *x;
} );
}
We can rewrite g
to access my_info
using LEAF:
#include <boost/leaf/handle_errors.hpp>
void g()
{
leaf::try_catch(
[]
{
f();
},
[]( my_info x )
{
std::cerr << "Got my_info with value = " << x.value();
} );
}
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 match
is also supported:
void g()
{
leaf::try_catch(
[]
{
f();
},
[]( leaf::match_value<my_info, 42> )
{
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
See github.
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 see Distribution.
Error Reporting
error.hpp
namespace boost { namespace leaf {
class error_id
{
public:
error_id() noexcept;
template <class Enum>
error_id( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::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 <class... Item>
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 <class... Item>
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 Ctx>
class context_activator
{
context_activator( context_activator const & ) = delete;
context_activator & operator=( context_activator const & ) = delete;
public:
explicit context_activator( Ctx & ctx ) noexcept;
context_activator( context_activator && ) noexcept;
~context_activator() noexcept;
};
template <class Ctx>
context_activator<Ctx> activate_context( Ctx & ctx ) noexcept;
template <class R>
struct is_result_type: std::false_type
{
};
template <class R>
struct is_result_type<R const>: is_result_type<R>
{
};
} }
#define BOOST_LEAF_ASSIGN(v, r)\
auto && <<temp>> = r;\
if( !<<temp>> )\
return <<temp>>.error();\
v = std::forward<decltype(<<temp>>)>(<<temp>>).value()
#define BOOST_LEAF_AUTO(v, r)\
BOOST_LEAF_ASSIGN(auto v, r)
#define BOOST_LEAF_CHECK(r)\
auto && <<temp>> = r;\
if( <<temp>> )\
;\
else\
return <<temp>>.error()
#define BOOST_LEAF_NEW_ERROR <<inject e_source_location voodoo>> ::boost::leaf::new_error
Reference: error_id
| is_error_id
| new_error
| current_error
| polymorphic_context
| context_activator
| activate_context
| is_result_type
| BOOST_LEAF_ASSIGN
| BOOST_LEAF_AUTO
| BOOST_LEAF_CHECK
| BOOST_LEAF_NEW_ERROR
common.hpp
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 & );
};
}
} }
Reference: e_api_function
| e_file_name
| e_at_line
| e_type_info_name
| e_source_location
| e_errno
| e_LastError
result.hpp
namespace boost { namespace leaf {
template <class T>
class result
{
public:
result() noexcept;
result( T && v ) noexcept;
result( T const & v );
template <class U>
result( U && u, <<enabled_if_T_can_be_inited_with_U>> );
result( error_id err ) noexcept;
result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;
template <class Enum>
result( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::value, Enum>::type * = 0 ) noexcept;
result( std::error_code const & ec ) noexcept;
result( result && r ) noexcept;
template <class U>
result( result<U> && r ) noexcept;
result & operator=( result && r ) noexcept;
template <class U>
result & operator=( result<U> && r ) noexcept;
explicit operator bool() const noexcept;
T const & value() const;
T & value();
T const & operator*() const;
T & operator*();
T const * operator->() const;
T * operator->();
<<unspecified-type>> error() noexcept;
template <class... Item>
error_id load( Item && ... item ) noexcept;
};
template <>
class result<void>
{
public:
result() noexcept;
result( error_id err ) noexcept;
result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;
template <class Enum>
result( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::value, Enum>::type * = 0 ) noexcept;
result( std::error_code const & ec ) noexcept;
result( result && r ) noexcept;
template <class U>
result( result<U> && r ) noexcept;
result & operator=( result && r ) noexcept;
template <class U>
result & operator=( result<U> && r ) noexcept;
explicit operator bool() const noexcept;
void value() const;
<<unspecified-type>> error() noexcept;
template <class... Item>
error_id load( Item && ... item ) noexcept;
};
struct bad_result: std::exception { };
template <class T>
struct is_result_type<result<T>>: std::true_type
{
};
} }
Reference: result
| is_result_type
on_error.hpp
namespace boost { namespace leaf {
template <class... Item>
<<unspecified-type>> on_error( Item && ... e ) noexcept;
class error_monitor
{
public:
error_monitor() noexcept;
error_id check() const noexcept;
error_id assigned_error_id() const noexcept;
};
} }
Reference: on_error
| error_monitor
exception.hpp
namespace boost { namespace leaf {
template <class Ex, class... E> (1)
<<unspecified-exception-type>> exception( Ex &&, E && ... ) noexcept;
template <class E1, class... E> (2)
<<unspecified-exception-type>> exception( E1 &&, E && ... ) noexcept;
<<unspecified-exception-type>> exception() noexcept;
template <class Ex, class... E> (1)
<<unspecified-exception-type>> exception( error_id id, Ex &&, E && ... ) noexcept;
template <class E1, class... E> (2)
<<unspecified-exception-type>> exception( error_id id, E1 &&, E && ... ) noexcept;
<<unspecified-exception-type>> exception( error_id id ) noexcept;
} }
#define BOOST_LEAF_EXCEPTION <<inject e_source_location voodoo>> ::boost::leaf::exception
#define BOOST_LEAF_THROW_EXCEPTION <<inject e_source_location + invoke boost::throw_exception voodoo>> ::boost::leaf::exception
Reference: exception
| BOOST_LEAF_EXCEPTION
| BOOST_LEAF_THROW_EXCEPTION
1 | Only enabled if std::is_base_of<std::exception, Ex>::value. |
2 | Only enabled if !std::is_base_of<std::exception, E1>::value. |
capture.hpp
namespace boost { namespace leaf {
template <class F, class... A>
decltype(std::declval<F>()(std::forward<A>(std::declval<A>())...))
capture(std::shared_ptr<polymorphic_context> && ctx, F && f, A... a);
template <class... Ex, class F>
<<result<T>-deduced>> exception_to_result( F && f ) noexcept;
} }
Reference: capture
| exception_to_result
Error Handling
context.hpp
namespace boost { namespace leaf {
template <class... E>
class context
{
context( context const & ) = delete;
context & operator=( context const & ) = delete;
public:
context() noexcept;
context( context && x ) noexcept;
~context() noexcept;
void activate() noexcept;
void deactivate() noexcept;
bool is_active() const noexcept;
void propagate () noexcept;
void print( std::ostream & os ) const;
template <class R, class... H>
R handle_error( R &, H && ... ) const;
};
//////////////////////////////////////////
template <class... H>
using context_type_from_handlers = typename <<unspecified>>::type;
template <class... H>
BOOST_LEAF_CONSTEXPR context_type_from_handlers<H...> make_context() noexcept;
template <class... H>
BOOST_LEAF_CONSTEXPR context_type_from_handlers<H...> make_context( H && ... ) noexcept;
template <class... H>
context_ptr make_shared_context() noexcept;
template <class... H>
context_ptr make_shared_context( H && ... ) noexcept;
} }
Reference: context
| context_type_from_handlers
| make_context
| make_shared_context
handle_errors.hpp
namespace boost { namespace leaf {
template <class TryBlock, class... H>
typename std::decay<decltype(std::declval<TryBlock>()().value())>::type
try_handle_all( TryBlock && try_block, H && ... h );
template <class TryBlock, class... H>
typename std::decay<decltype(std::declval<TryBlock>()())>::type
try_handle_some( TryBlock && try_block, H && ... h );
template <class TryBlock, class... H>
typename std::decay<decltype(std::declval<TryBlock>()())>::type
try_catch( TryBlock && try_block, H && ... h );
//////////////////////////////////////////
class error_info
{
//No public constructors
public:
error_id error() const noexcept;
bool exception_caught() const noexcept;
std::exception const * exception() const noexcept;
friend std::ostream & operator<<( std::ostream & os, error_info const & x );
};
class diagnostic_info: public error_info
{
//No public constructors
friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x );
};
class verbose_diagnostic_info: public error_info
{
//No public constructors
friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x );
};
} }
Reference: try_handle_all
| try_handle_some
| try_catch
| error_info
| diagnostic_info
| verbose_diagnostic_info
pred.hpp
namespace boost { namespace leaf {
template <class T>
struct is_predicate: std::false_type
{
};
template <class E, auto... V>
struct match
{
E matched;
// Other members not specified
};
template <class E, auto... V>
struct is_predicate<match<E, V...>>: std::true_type
{
};
template <class E, auto... V>
struct match_value
{
E matched;
// Other members not specified
};
template <class E, auto... V>
struct is_predicate<match_value<E, V...>>: std::true_type
{
};
template <auto, auto...>
struct match_member;
template <class E, class T, T E::* P, auto... V>
struct member<P, V...>
{
E matched;
// Other members not specified
};
template <auto P, auto... V>
struct is_predicate<match_member<P, V...>>: std::true_type
{
};
template <class... Ex>
struct catch_
{
std::exception const & matched;
// Other members not specified
};
template <class Ex>
struct catch_<Ex>
{
Ex const & matched;
// Other members not specified
};
template <class... Ex>
struct is_predicate<catch_<Ex...>>: std::true_type
{
};
template <class Pred>
struct if_not
{
E matched;
// Other members not specified
};
template <class Pred>
struct is_predicate<if_not<Pred>>: std::true_type
{
};
template <class ErrorCodeEnum>
bool category( std::error_code const & ec ) noexcept;
template <class Enum, class EnumType = Enum>
struct condition;
} }
Reference: match
| match_value
| match_member
| catch_
| if_not
| category
| condition
Reference: Functions
The contents of each Reference section are organized alphabetically. |
activate_context
namespace boost { namespace leaf {
template <class Ctx>
context_activator<Ctx> activate_context( Ctx & ctx ) noexcept
{
return context_activator<Ctx>(ctx);
}
} }
leaf::context<E1, E2, E3> ctx;
{
auto active_context = activate_context(ctx); (1)
} (2)
1 | Activate ctx . |
2 | Automatically deactivate ctx . |
capture
namespace boost { namespace leaf {
template <class F, class... A>
decltype(std::declval<F>()(std::forward<A>(std::declval<A>())...))
capture(std::shared_ptr<polymorphic_context> && ctx, F && f, A... a);
} }
This function can be used to capture error objects stored in a context
in one thread and transport them to a different thread for handling, either in a result<T>
object or in an exception.
- Returns:
-
The same type returned by
F
. - Effects:
-
Uses an internal
context_activator
toactivate
*ctx
, then invokesstd::forward<F>(f)(std::forward<A>(a)…)
. Then:-
If the returned value
r
is not aresult<T>
type (seeis_result_type
), it is forwarded to the caller. -
Otherwise:
-
If
!r
, the return value ofcapture
is initialized withctx
;An object of type leaf::result<T>
can be initialized with astd::shared_ptr<leaf::polymorphic_context>
. -
otherwise, it is initialized with
r
.
-
In case
f
throws,capture
catches the exception in astd::exception_ptr
, and throws a different exception of unspecified type that transports both thestd::exception_ptr
as well asctx
. This exception type is recognized bytry_catch
, which automatically unpacks the original exception and propagates the contents of*ctx
(presumably, in a different thread). -
See also Transporting Error Objects Between Threads from the Tutorial. |
context_type_from_handlers
namespace boost { namespace leaf {
template <class... H>
using context_type_from_handlers = typename <<unspecified>>::type;
} }
auto error_handlers = std::make_tuple(
[](e_this const & a, e_that const & b)
{
....
},
[](leaf::diagnostic_info const & info)
{
....
},
.... );
leaf::context_type_from_handlers<decltype(error_handlers)> ctx; (1)
1 | ctx will be of type context<e_this, e_that> , deduced automatically from the specified error handlers. |
Alternatively, a suitable context may be created by calling make_context , or allocated dynamically by calling make_shared_context .
|
current_error
namespace boost { namespace leaf {
error_id current_error() noexcept;
} }
- Returns:
-
The
error_id
value returned the last timenew_error
was invoked from the calling thread.
See also on_error .
|
exception
namespace boost { namespace leaf {
template <class Ex, class... E> (1)
<<unspecified>> exception( Ex && ex, E && ... e ) noexcept;
template <class E1, class... E> (2)
<<unspecified>> exception( E1 && e1, E && ... e ) noexcept;
<<unspecified>> exception() noexcept; (3)
template <class Ex, class... E> (4)
<<unspecified>> exception( error_id id, Ex && ex, E && ... e ) noexcept;
template <class E1, class... E> (5)
<<unspecified>> exception( error_id id, E1 && e1, E && ... e ) noexcept;
<<unspecified>> exception( error_id id ) noexcept; (6)
} }
The exception
function is overloaded: it can be invoked with no arguments, or else there are several alternatives, selected using std::enable_if
based on the type of the passed arguments:
1 | Selected if the first argument is not of type error_id and is an exception object, that is, iff Ex derives publicly from std::exception . In this case the return value is of unspecified type which derives publicly from Ex and from class error_id , such that:
|
2 | Selected if the first argument is not of type error_id and is not an exception object. In this case the return value is of unspecified type which derives publicly from std::exception and from class error_id , such that:
|
3 | If the fuction is invoked without arguments, the return value is of unspecified type which derives publicly from std::exception and from class error_id , such that:
|
4 | Selected if the first argument is of type error_id and the second argument is an exception object, that is, iff Ex derives publicly from std::exception . In this case the return value is of unspecified type which derives publicly from Ex and from class error_id , such that:
|
5 | Selected if the first argument is of type error_id and the second argument is not an exception object. In this case the return value is of unspecified type which derives publicly from std::exception and from class error_id , such that:
|
6 | If exception is invoked with just an error_id object, the return value is of unspecified type which derives publicly from std::exception and from class error_id , such that:
|
The first three overloads return an exception object that is associated with a new error_id . The second three overloads return an exception object that is associated with the specified error_id .
|
struct my_exception: std::exception { };
throw leaf::exception(my_exception{}); (1)
1 | Throws an exception of a type that derives from error_id and from my_exception (because my_exception derives from std::exception ). |
enum class my_error { e1=1, e2, e3 }; (1)
throw leaf::exception(my_error::e1);
1 | Throws an exception of a type that derives from error_id and from std::exception (because my_error does not derive from std::exception ). |
To automatically capture __FILE__ , __LINE__ and __FUNCTION__ with the returned object, use BOOST_LEAF_EXCEPTION instead of leaf::exception .
|
exception_to_result
namespace boost { namespace leaf {
template <class... Ex, class F>
<<result<T>-deduced>> exception_to_result( F && f ) noexcept;
} }
This function can be used to catch exceptions from a lower-level library and convert them to result<T>
.
- Returns:
-
Where
f
returns a typeT
,exception_to_result
returnsleaf::result<T>
. - Effects:
-
-
Catches all exceptions, then captures
std::current_exception
in astd::exception_ptr
object, which is loaded with the returnedresult<T>
. -
Attempts to convert the caught exception, using
dynamic_cast
, to each typeExi
inEx…
. If the cast toExi
succeeds, theExi
slice of the caught exception is loaded with the returnedresult<T>
.
-
An error handler that takes an argument of an exception type (that is, of a type that derives from std::exception ) will work correctly whether the object is thrown as an exception or communicated via new_error (or converted using exception_to_result ).
|
int compute_answer_throws();
//Call compute_answer, convert exceptions to result<int>
leaf::result<int> compute_answer()
{
return leaf::exception_to_result<ex_type1, ex_type2>(compute_answer_throws());
}
At a later time we can invoke try_handle_some
/ try_handle_all
as usual, passing handlers that take ex_type1
or ex_type2
, for example by reference:
return leaf::try_handle_some(
[] -> leaf::result<void>
{
BOOST_LEAF_AUTO(answer, compute_answer());
//Use answer
....
return { };
},
[](ex_type1 & ex1)
{
//Handle ex_type1
....
return { };
},
[](ex_type2 & ex2)
{
//Handle ex_type2
....
return { };
},
[](std::exception_ptr const & p)
{
//Handle any other exception from compute_answer.
....
return { };
} );
When a handler takes an argument of an exception type (that is, a type that derives from std::exception ), if the object is thrown, the argument will be matched dynamically (using dynamic_cast ); otherwise (e.g. after being converted by exception_to_result ) it will be matched based on its static type only (which is the same behavior used for types that do not derive from std::exception ).
|
See also Converting Exceptions to result<T> from the tutorial.
|
make_context
namespace boost { namespace leaf {
template <class... H>
context_type_from_handlers<H...> make_context() noexcept
{
return { };
}
template <class... H>
context_type_from_handlers<H...> make_context( H && ... ) noexcept
{
return { };
}
} }
auto ctx = leaf::make_context( (1)
[]( e_this ) { .... },
[]( e_that ) { .... } );
1 | decltype(ctx) is leaf::context<e_this, e_that> . |
make_shared_context
namespace boost { namespace leaf {
template <class... H>
context_ptr make_shared_context() noexcept
{
return std::make_shared<leaf_detail::polymorphic_context_impl<context_type_from_handlers<H...>>>();
}
template <class... H>
context_ptr make_shared_context( H && ... ) noexcept
{
return std::make_shared<leaf_detail::polymorphic_context_impl<context_type_from_handlers<H...>>>();
}
} }
See also Transporting Error Objects Between Threads from the tutorial. |
new_error
namespace boost { namespace leaf {
template <class... Item>
error_id new_error(Item && ... item) noexcept;
} }
- Requires:
-
Each of the
Item…
types must be no-throw movable. - Effects:
-
As if:
error_id id = <<generate-new-unique-id>>; return id.load(std::forward<Item>(item)...);
- Returns:
-
A new
error_id
value, which is unique across the entire program. - Ensures:
-
id.value()!=0
, whereid
is the returnederror_id
.
new_error discards error objects which are not used in any active error handling calling scope.
|
When loaded into a context , an error object of a type E will overwrite the previously loaded object of type E , if any.
|
on_error
namespace boost { namespace leaf {
template <class... Item>
<<unspecified-type>> on_error(Item && ... item) noexcept;
} }
- Requires:
-
Each of the
Item…
types must be no-throw movable. - Effects:
-
All
item…
objects are forwarded and stored, together with the value returned fromstd::unhandled_exceptions
, into the returned object of unspecified type, which should be captured byauto
and kept alive in the calling scope. When that object is destroyed, if an error has occurred sinceon_error
was invoked, LEAF will process the stored items to obtain error objects to be associated with the failure.On error, LEAF first needs to deduce an
error_id
valueerr
to associate error objects with. This is done using the following logic:-
If
new_error
was invoked (by the calling thread) since the object returned byon_error
was created,err
is initialized with the value returned bycurrent_error
; -
Otherwise, if
std::unhandled_exceptions
returns a greater value than it returned during initialization,err
is initialized with the value returned bynew_error
; -
Otherwise, the stored
item…
objects are discarded and no further action is taken (no error has occurred).
Next, LEAF proceeds similarly to:
err.load(std::forward<Item>(item)...);
The difference is that unlike
load
,on_error
will not overwrite any error objects already associated witherr
. -
See Using on_error from the Tutorial.
|
try_catch
namespace boost { namespace leaf {
template <class TryBlock, class... H>
typename std::decay<decltype(std::declval<TryBlock>()())>::type
try_catch( TryBlock && try_block, H && ... h );
} }
The try_catch
function works similarly to try_handle_some
, except that it does not use or understand the semantics of result<T>
types; instead:
-
It assumes that the
try_block
throws to indicate a failure, in which casetry_catch
will attempt to find a suitable handler amongh…
; -
If a suitable handler isn’t found, the original exception is re-thrown using
throw;
.
See also Exception Handling from the Tutorial section. |
try_handle_all
namespace boost { namespace leaf {
template <class TryBlock, class... H>
typename std::decay<decltype(std::declval<TryBlock>()().value())>::type
try_handle_all( TryBlock && try_block, H && ... h );
} }
The try_handle_all
function works similarly to try_handle_some
, except:
-
In addition, it requires that at least one of
h…
can be used to handle any error (this requirement is enforced at compile time); -
If the
try_block
returns someresult<T>
type, it must be possible to initialize a value of typeT
with the value returned by each ofh…
, and -
Because it is required to handle all errors,
try_handle_all
unwraps theresult<T>
objectr
returned by thetry_block
, returningr.value()
instead ofr
.
See also Error Handling from the Tutorial section. |
try_handle_some
namespace boost { namespace leaf {
template <class TryBlock, class... H>
typename std::decay<decltype(std::declval<TryBlock>()())>::type
try_handle_some( TryBlock && try_block, H && ... h );
} }
- Requires:
-
-
The
try_block
function may not take any arguments. -
The type
R
returned by thetry_block
function must be aresult<T>
type (seeis_result_type
). It is valid for thetry_block
to returnleaf::result<T>
, however this is not a requirement. -
Each of the
h…
functions:-
must return a type that can be used to initialize an object of the type
R
; in case R is aresult<void>
(that is, in case of success it does not communicate a value), handlers that returnvoid
are permitted. If such a handler is selected, thetry_handle_some
return value is initialized by{}
; -
may take any error objects, by value, by (
const
) reference, or as pointer (toconst
); -
may take arguments, by value, of any predicate type:
catch_
,match
,match_value
,match_member
,if_not
, or of any user-defined predicate typePred
for whichis_predicate<Pred>::value
istrue
; -
may take an
error_info
argument byconst &
; -
may take a
diagnostic_info
argument byconst &
; -
may take a
verbose_diagnostic_info
argument byconst &
.
-
-
- Effects:
-
-
Creates a local
context<E…>
objectctx
, where theE…
types are automatically deduced from the types of arguments taken by each ofh…
, which guarantees thatctx
is able to store all of the types required to handle errors. -
Invokes the
try_block
:-
if the returned object
r
indicates success and thetry_block
did not throw,r
is forwarded to the caller. -
otherwise, LEAF considers each of the
h…
handlers, in order, until it finds one that it can supply with arguments using the error objects currently stored inctx
, associated withr.error()
. The first such handler is invoked and its return value is used to initialize the return value oftry_handle_some
, which can indicate success if the handler was able to handle the error, or failure if it was not. -
if
try_handle_some
is unable to find a suitable handler, it returnsr
.
-
-
try_handle_some is exception-neutral: it does not throw exceptions, however the try_block and any of h… are permitted to throw.
|
- Handler Selection Procedure:
-
A handler
h
is suitable to handle the failure reported byr
ifftry_handle_some
is able to produce values to pass as its arguments, using the error objects currently available inctx
, associated with the error ID obtained by callingr.error()
. As soon as it is determined that an argument value can not be produced, the current handler is dropped and the selection process continues with the next handler, if any.The return value of
r.error()
must be implicitly convertible toerror_id
. Naturally, theleaf::result
template satisfies this requirement. If an externalresult
type is used instead, usuallyr.error()
would return astd::error_code
, which is able to communicate LEAF error IDs; see Interoperability.If
err
is theerror_id
obtained fromr.error()
, each argumentai
taken by the handler currently under consideration is produced as follows:-
If
ai
is of typeAi
,Ai const&
orAi&
:-
If an error object of type
Ai
, associated witherr
, is currently available inctx
,ai
is initialized with a reference to that object; otherwise -
If
Ai
derives fromstd::exception
, and thetry_block
throws an objectex
of type that derives fromstd::exception
, LEAF obtainsAi* p = dynamic_cast<Ai*>(&ex)
. The handler is dropped ifp
is null, otherwiseai
is initialized with*p
. -
Otherwise the handler is dropped.
Example:.... auto r = leaf::try_handle_some( []() -> leaf::result<int> { return f(); }, [](leaf::e_file_name const & fn) (1) { std::cerr << "File Name: \"" << fn.value << '"' << std::endl; (2) return 1; } );
1 In case the try_block
indicates a failure, this handler will be selected ifctx
stores ane_file_name
associated with the error. Because this is the only supplied handler, if ane_file_name
is not available,try_handle_some
will return theleaf::result<int>
returned byf
.2 Print the file name, handle the error. -
-
If
ai
is of typeAi
const*
orAi*
,try_handle_some
is always able to produce it: first it attempts to produce it as if it is taken by reference; if that fails, rather than dropping the handler,ai
is initialized with0
.Example:.... try_handle_some( []() -> leaf::result<int> { return f(); }, [](leaf::e_file_name const * fn) (1) { if( fn ) (2) std::cerr << "File Name: \"" << fn->value << '"' << std::endl; return 1; } ); }
1 This handler can be selected to handle any error, because it takes e_file_name
as aconst *
(and nothing else).2 If an e_file_name
is available with the current error, print it. -
If
ai
is of a predicate typePred
(for whichis_predicate<Pred>::value
istrue
),E
is deduced astypename Pred::error_type
, and then:-
If
E
is notvoid
, and an error objecte
of typeE
, associated witherr
, is not currently stored inctx
, the handler is dropped; otherwise the handler is dropped if the expressionPred::evaluate(e)
returnsfalse
. -
if
E
isvoid
, and astd::exception
was not caught, the handler is dropped; otherwise the handler is dropped if the expressionPred::evaluate(e)
, wheree
is of typestd::exception const &
, returnsfalse
. -
To invoke the handler, the
Pred
argumentai
is initialized withPred{e}
.See also: Predicates.
-
-
If
ai
is of typeerror_info const &
,try_handle_some
is always able to produce it.Example:.... try_handle_some( [] { return f(); // returns leaf::result<T> }, [](leaf::error_info const & info) (1) { std::cerr << "leaf::error_info:" << std::endl << info; (2) return info.error(); (3) } );
1 This handler matches any error. 2 Print error information. 3 Return the original error, which will be returned out of try_handle_some
. -
If
ai
is of typediagnostic_info const &
,try_handle_some
is always able to produce it.Example:.... try_handle_some( [] { return f(); // throws }, [](leaf::diagnostic_info const & info) (1) { std::cerr << "leaf::diagnostic_information:" << std::endl << info; (2) return info.error(); (3) } );
1 This handler matches any error. 2 Print diagnostic information, including limited information about dropped error objects. 3 Return the original error, which will be returned out of try_handle_some
. -
If
ai
is of typeverbose_diagnostic_info const &
,try_handle_some
is always able to produce it.Example:.... try_handle_some( [] { return f(); // throws }, [](leaf::verbose_diagnostic_info const & info) (1) { std::cerr << "leaf::verbose_diagnostic_information:" << std::endl << info; (2) return info.error(); (3) } );
1 This handler matches any error. 2 Print verbose diagnostic information, including values of dropped error objects. 3 Return the original error, which will be returned out of try_handle_some
.
-
Reference: Types
The contents of each Reference section are organized alphabetically. |
context
namespace boost { namespace leaf {
template <class... E>
class context
{
context( context const & ) = delete;
context & operator=( context const & ) = delete;
public:
context() noexcept;
context( context && x ) noexcept;
~context() noexcept;
void activate() noexcept;
void deactivate() noexcept;
bool is_active() const noexcept;
void propagate() noexcept;
void print( std::ostream & os ) const;
template <class R, class... H>
R handle_error( error_id, H && ... ) const;
};
template <class... H>
using context_type_from_handlers = typename <<unspecified>>::type;
} }
Constructors | activate
| deactivate
| is_active
| propagate
| print
| handle_error
| context_type_from_handlers
The context
class template provides storage for each of the specified E…
types. Typically, context
objects are not used directly; they’re created internally when the try_handle_some
, try_handle_all
or try_catch
functions are invoked, instantiated with types that are automatically deduced from the types of the arguments of the passed handlers.
Independently, users can create context
objects if they need to capture error objects and then transport them, by moving the context
object itself.
Even in that case it is recommended that users do not instantiate the context
template by explicitly listing the E…
types they want it to be able to store. Instead, use context_type_from_handlers
or call the make_context
function template, which deduce the correct E…
types from a captured list of handler function objects.
To be able to load up error objects in a context
object, it must be activated. Activating a context
object ctx
binds it to the calling thread, setting thread-local pointers of the stored E…
types to point to the corresponding storage within ctx
. It is possible, even likely, to have more than one active context
in any given thread. In this case, activation/deactivation must happen in a LIFO manner. For this reason, it is best to use a context_activator
, which relies on RAII to activate and deactivate a context
.
When a context
is deactivated, it detaches from the calling thread, restoring the thread-local pointers to their pre-activate
values. Typically, at this point the stored error objects, if any, are either discarded (by default) or moved to corresponding storage in other context
objects active in the calling thread (if available), by calling propagate
.
While error handling typically uses try_handle_some
, try_handle_all
or try_catch
, it is also possible to handle errors by calling the member function handle_error
. It takes an error_id
, and attempts to select an error handler based on the error objects stored in *this
, associated with the passed error_id
.
context objects can be moved, as long as they aren’t active.
|
Moving an active context results in undefined behavior.
|
Constructors
namespace boost { namespace leaf {
template <class... E>
context<E...>::context() noexcept;
template <class... E>
context<E...>::context( context && x ) noexcept;
} }
The default constructor initializes an empty context
object: it provides storage for, but does not contain any error objects.
The move constructor moves the stored error objects from one context
to the other.
Moving an active context object results in undefined behavior.
|
activate
namespace boost { namespace leaf {
template <class... E>
void context<E...>::activate() noexcept;
} }
When a context is associated with a thread, thread-local pointers are set to point each E…
type in its store, while the previous value of each such pointer is preserved in the context
object, so that the effect of activate
can be undone by calling deactivate
.
When an error object is loaded, it is moved in the last activated (in the calling thread) context
object that provides storage for its type (note that this may or may not be the last activated context
object). If no such storage is available, the error object is discarded.
deactivate
namespace boost { namespace leaf {
template <class... E>
void context<E...>::deactivate() noexcept;
} }
When a context is deactivated, the thread-local pointers that currently point to each individual error object storage in it are restored to their original value prior to calling activate
.
handle_error
namespace boost { namespace leaf {
template <class... E>
template <class R, class... H>
R context<E...>::handle_error( error_id err, H && ... h ) const;
} }
This function works similarly to try_handle_all
, but rather than calling a try_block
and obtaining the error_id
from a returned result
type, it matches error objects (stored in *this
, associated with err
) with a suitable error handler from the h…
pack.
The caller is required to specify the return type R . This is because in general the supplied handlers may return different types (which must all be convertible to R ).
|
is_active
namespace boost { namespace leaf {
template <class... E>
bool context<E...>::is_active() const noexcept;
} }
- Returns:
-
true
if the*this
is active in any thread,false
otherwise.
print
namespace boost { namespace leaf {
template <class... E>
void context<E...>::print( std::ostream & os ) const;
} }
- Effects:
-
Prints all error objects currently stored in
*this
, together with the unique error ID each individual error object is associated with.
propagate
namespace boost { namespace leaf {
template <class... E>
void context<E...>::propagate() noexcept;
} }
- Requires:
-
!is_active()
. - Effects:
-
Each stored error object of some type
E
is moved into anothercontext
object active in the call stack that provides storage for objects of typeE
, if any, or discarded.
context_activator
namespace boost { namespace leaf {
template <class Ctx>
class context_activator
{
context_activator( context_activator const & ) = delete;
context_activator & operator=( context_activator const & ) = delete;
public:
explicit context_activator( Ctx & ctx ) noexcept;
context_activator( context_activator && ) noexcept;
~context_activator() noexcept;
};
} }
context_activator
is a simple class that activates and deactivates a context
using RAII:
If ctx.is_active
() is true
at the time the context_activator
is initialized, the constructor and the destructor have no effects. Otherwise:
-
The constructor stores a reference to
ctx
in*this
and callsctx.activate
(). -
The destructor:
-
Has no effects if
ctx.is_active()
isfalse
(that is, it is valid to calldeactivate
manually, before thecontext_activator
object expires); -
Otherwise, calls
ctx.deactivate
() and, if there are new uncaught exceptions since the constructor was called, the destructor callsctx.propagate
().
-
For automatic deduction of Ctx
, use activate_context
.
diagnostic_info
namespace boost { namespace leaf {
class diagnostic_info: public error_info
{
//Constructors unspecified
friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x );
};
} }
Handlers passed to try_handle_some
, try_handle_all
or try_catch
may take an argument of type diagnostic_info const &
if they need to print diagnostic information about the error.
The message printed by operator<<
includes the message printed by error_info
, followed by basic information about error objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active context
(these error objects were discarded by LEAF, because no handler needed them).
The additional information is limited to the type name of the first such error object, as well as their total count.
The behavior of
|
error_id
namespace boost { namespace leaf {
class error_id
{
public:
error_id() noexcept;
template <class Enum>
result( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::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 noexcept;
friend bool operator==( error_id a, error_id b ) noexcept;
friend bool operator!=( error_id a, error_id b ) noexcept;
friend bool operator<( error_id a, error_id b ) noexcept;
template <class... Item>
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 <class... E>
error_id new_error( E && ... e ) noexcept;
error_id current_error() noexcept;
} }
Constructors | value
| operator bool
| to_error_code
| operator==
, !=
, <
| load
| is_error_id
| new_error
| current_error
Values of type error_id
identify a specific occurrence of a failure across the entire program. They can be copied, moved, assigned to, and compared to other error_id
objects. They’re as efficient as an int
.
Constructors
namespace boost { namespace leaf {
error_id::error_id() noexcept = default;
template <class Enum>
error_id::error_id( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::value, Enum>::type * = 0 ) noexcept;
error_id::error_id( std::error_code const & ec ) noexcept;
} }
A default-initialized error_id
object does not represent a specific failure. It compares equal to any other default-initialized error_id
object. All other error_id
objects identify a specific occurrence of a failure.
When using an object of type error_id to initialize a result<T> object, it will be initialized in error state, even when passing a default-initialized error_id value.
|
Converting an error_id
object to std::error_code
uses an unspecified std::error_category
which LEAF recognizes. This allows an error_id
to be transported through interfaces that work with std::error_code
. The std::error_code
constructor allows the original error_id
to be restored.
To check if a given std::error_code is actually carrying an error_id , use is_error_id .
|
Typically, users create new error_id
objects by invoking new_error
. The constructor that takes std::error_code
, and the one that takes a type Enum
for which std::is_error_code_enum<Enum>::value
is true
, have the following effects:
-
If
ec.value()
is0
, the effect is the same as using the default constructor. -
Otherwise, if
is_error_id(ec)
istrue
, the originalerror_id
value is used to initialize*this
; -
Otherwise,
*this
is initialized by the value returned bynew_error
, whileec
is passed toload
, which enables handlers used withtry_handle_some
,try_handle_all
ortry_catch
to receive it as an argument of typestd::error_code
.
is_error_id
namespace boost { namespace leaf {
bool is_error_id( std::error_code const & ec ) noexcept;
} }
- Returns:
-
true
ifec
uses the LEAF-specificstd::error_category
that identifies it as carrying an error ID rather than another error code; otherwise returnsfalse
.
load
namespace boost { namespace leaf {
template <class... Item>
error_id error_id::load( Item && ... item ) const noexcept;
} }
- Requires:
-
Each of the
Item…
types must be no-throw movable. - Effects:
-
-
If
value()==0
, all ofitem…
are discarded and no further action is taken. -
Otherwise, what happens with each
item
depends on its type:-
If it is a function that takes a single argument of some type
E &
, that function is called with the object of typeE
currently associated with*this
. If no such object exists, a default-initialized object is associated with*this
and then passed to the function. -
If it is a function that takes no arguments, than function is called to obtain an error object, which is associated with
*this
. -
Otherwise, the
item
itself is assumed to be an error object, which is associated with*this
.
-
-
- Returns:
-
*this
.
load discards error objects which are not used in any active error handling calling scope.
|
When loaded into a context , an error object of a type E will overwrite the previously loaded object of type E , if any.
|
- See also:
operator==
, !=
, <
namespace boost { namespace leaf {
friend bool operator==( error_id a, error_id b ) noexcept;
friend bool operator!=( error_id a, error_id b ) noexcept;
friend bool operator<( error_id a, error_id b ) noexcept;
} }
These functions have the usual semantics, comparing a.value()
and b.value()
.
The exact strict weak ordering implemented by operator< is not specified. In particular, if for two error_id objects a and b , a < b is true, it does not follow that the failure identified by a ocurred earlier than the one identified by b .
|
operator bool
namespace boost { namespace leaf {
explicit error_id::operator bool() const noexcept;
} }
- Effects:
-
As if
return value()!=0
.
to_error_code
namespace boost { namespace leaf {
std::error_code error_id::to_error_code() const noexcept;
} }
- Effects:
-
Returns a
std::error_code
with the samevalue()
as*this
, using an unspecifiedstd::error_category
.
The returned object can be used to initialize an error_id , in which case the original error_id value will be restored.
|
Use is_error_id to check if a given std::error_code carries an error_id .
|
value
namespace boost { namespace leaf {
int error_id::value() const noexcept;
} }
- Effects:
-
-
If
*this
was initialized using the default constructor, returns 0. -
Otherwise returns an
int
that is guaranteed to not be 0: a program-wide unique identifier of the failure.
-
error_monitor
namespace boost { namespace leaf {
class error_monitor
{
public:
error_monitor() noexcept;
error_id check() const noexcept;
error_id assigned_error_id( E && ... e ) const noexcept;
};
} }
This class helps obtain an error_id
to associate error objects with, when augmenting failures communicated using LEAF through uncooperative APIs that do not use LEAF to report errors (and therefore do not return an error_id
on error).
The common usage of this class is as follows:
error_code compute_value( int * out_value ) noexcept; (1)
leaf::error<int> augmenter() noexcept
{
leaf::error_monitor cur_err; (2)
int val;
auto ec = compute_value(&val);
if( failure(ec) )
return cur_err.assigned_error_id().load(e1, e2, ...); (3)
else
return val; (4)
}
1 | Uncooperative third-party API that does not use LEAF, but may result in calling a user callback that does use LEAF. In case our callback reports a failure, we’ll augment it with error objects available in the calling scope, even though compute_value can not communicate an error_id . |
2 | Initialize an error_monitor object. |
3 | The call to compute_value has failed:
|
4 | The call was successful, return the computed value. |
The check
function works similarly, but instead of invoking new_error
it returns a default-initialized error_id
.
e_api_function
namespace boost { namespace leaf {
struct e_api_function {char const * value;};
} }
The e_api_function
type is designed to capture the name of the API function that failed. For example, if you’re reporting an error from fread
, you could use leaf::e_api_function {"fread"}
.
The passed value is stored as a C string (char const * ), so value should only be initialized with a string literal.
|
e_at_line
namespace boost { namespace leaf {
struct e_at_line { int value; };
} }
e_at_line
can be used to communicate the line number when reporting errors (for example parse errors) about a text file.
e_errno
namespace boost { namespace leaf {
struct e_errno
{
int value;
friend std::ostream & operator<<( std::ostream & os, e_errno const & err );
};
} }
To capture errno
, use e_errno
. When printed in automatically-generated diagnostic messages, e_errno
objects use strerror
to convert the errno
code to string.
e_file_name
namespace boost { namespace leaf {
struct e_file_name { std::string value; };
} }
When a file operation fails, you could use e_file_name
to store the name of the file.
It is probably better to define your own file name wrappers to avoid clashes if different modules all use leaf::e_file_name . It is best to use a descriptive name that clarifies what kind of file name it is (e.g. e_source_file_name , e_destination_file_name ), or at least define e_file_name in a given module’s namespace.
|
e_LastError
namespace boost { namespace leaf {
namespace windows
{
struct e_LastError
{
unsigned value;
friend std::ostream & operator<<( std::ostream & os, e_LastError const & err );
};
}
} }
e_LastError
is designed to communicate GetLastError()
values on Windows.
e_source_location
namespace boost { namespace leaf {
struct e_source_location
{
char const * const file;
int const line;
char const * const function;
friend std::ostream & operator<<( std::ostream & os, e_source_location const & x );
};
} }
The BOOST_LEAF_NEW_ERROR
, BOOST_LEAF_EXCEPTION
and BOOST_LEAF_THROW_EXCEPTION
macros capture __FILE__
, __LINE__
and __FUNCTION__
into a e_source_location
object.
e_type_info_name
namespace boost { namespace leaf {
struct e_type_info_name { char const * value; };
} }
e_type_info_name
is designed to store the return value of std::type_info::name
.
error_info
namespace boost { namespace leaf {
class error_info
{
//Constructors unspecified
public:
error_id error() const noexcept;
bool exception_caught() const noexcept;
std::exception const * exception() const noexcept;
friend std::ostream & operator<<( std::ostream & os, error_info const & x );
};
} }
Handlers passed to error handling functions such as try_handle_some
, try_handle_all
or try_catch
may take an argument of type error_info const &
to receive generic information about the error being handled.
The error
member function returns the program-wide unique error_id
of the error.
The exception_caught
member function returns true
if the handler that received *this
is being invoked to handle an exception, false
otherwise.
If handling an exception, the exception
member function returns a pointer to the std::exception
subobject of the caught exception, or 0
if that exception could not be converted to std::exception
.
It is illegal to call the exception member function unless exception_caught() is true .
|
The operator<<
overload prints diagnostic information about each error object currently stored in the context
local to the try_handle_some
, try_handle_all
or try_catch
scope that invoked the handler, but only if it is associated with the error_id
returned by error()
.
polymorphic_context
namespace boost { namespace leaf {
class polymorphic_context
{
protected:
polymorphic_context() noexcept;
~polymorphic_context() noexcept;
public:
virtual void activate() noexcept = 0;
virtual void deactivate() noexcept = 0;
virtual bool is_active() const noexcept = 0;
virtual void propagate() noexcept = 0;
virtual void print( std::ostream & ) const = 0;
};
} }
The polymorphic_context
class is an abstract base type which can be used to erase the type of the exact instantiation of the context
class template used. See make_shared_context
.
result
namespace boost { namespace leaf {
template <class T>
class result
{
public:
result() noexcept;
result( T && v ) noexcept;
result( T const & v );
template <class U>
result( U &&, <<enabled_if_T_can_be_inited_with_U>> );
result( error_id err ) noexcept;
result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;
template <class Enum>
result( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::value, Enum>::type * = 0 ) noexcept;
result( std::error_code const & ec ) noexcept;
result( result && r ) noexcept;
template <class U>
result( result<U> && r ) noexcept;
result & operator=( result && r ) noexcept;
template <class U>
result & operator=( result<U> && r ) noexcept;
explicit operator bool() const noexcept;
T const & value() const;
T & value();
T const & operator*() const;
T & operator*();
T const * operator->() const;
T * operator->();
<<unspecified-type>> error() noexcept;
template <class... Item>
error_id load( Item && ... item ) noexcept;
};
template <>
class result<void>
{
public:
result() noexcept;
result( error_id err ) noexcept;
result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;
template <class Enum>
result( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::value, Enum>::type * = 0 ) noexcept;
result( std::error_code const & ec ) noexcept;
result( result && r ) noexcept;
template <class U>
result( result<U> && r ) noexcept;
result & operator=( result && r ) noexcept;
template <class U>
result & operator=( result<U> && r ) noexcept;
explicit operator bool() const noexcept;
void value() const;
<<unspecified-type>> error() noexcept;
template <class... Item>
error_id load( Item && ... item ) noexcept;
};
struct bad_result: std::exception { };
} }
The result<T>
type can be returned by functions which produce a value of type T
but may fail doing so.
- Requires:
-
T
must be movable, and its move constructor may not throw. - Invariant:
-
A
result<T>
object is in one of three states:-
Value state, in which case it contains an object of type
T
, andvalue
/operator*
/operator->
can be used to access the contained value. -
Error state, in which case it contains an error ID, and calling
value
/operator*
/operator->
throwsleaf::bad_result
. -
Error capture state, which is the same as the Error state, but in addition to the error ID, it holds a
std::shared_ptr<polymorphic_context>
.
-
result<T>
objects are nothrow-moveable but are not copyable.
Constructors
namespace boost { namespace leaf {
template <class T>
result<T>::result() noexcept;
template <class T>
result<T>::result( T && v ) noexcept; (1)
template <class T>
result<T>::result( T const & v ); (1)
template <class U>
result<T>::result( U && u, <<enabled_if_T_can_be_inited_with_U>> ); (2)
template <class T>
result<T>::result( leaf::error_id err ) noexcept;
template <class T>
template <class Enum>
result<T>::result( Enum e, typename std::enable_if<std::is_error_code_enum<Enum>::value, Enum>::type * = 0 ) noexcept;
template <class T>
result<T>::result( std::error_code const & ec ) noexcept;
template <class T>
result<T>::result( std::shared_ptr<polymorphic_context> && ctx ) noexcept;
template <class T>
result<T>::result( result && ) noexcept;
template <class T>
template <class U>
result<T>::result( result<U> && ) noexcept;
} }
1 | Not available if T is void . |
2 | Available if an object of type T can be initialized with std::forward<U>(u) . This is to enable e.g. result<std::string> to be initialized with a string literal. |
- Requires:
-
T
must be movable, and its move constructor may not throw; orvoid
. - Effects:
-
Establishes the
result<T>
invariant:-
To get a
result<T>
in Value state, initialize it with an object of typeT
or use the default constructor. -
To get a
result<T>
in Error state, initialize it with:-
an
error_id
object.Initializing a result<T>
with a default-initializederror_id
object (for which.value()
returns0
) will still result in Error state! -
a
std::error_code
object. -
an object of type
Enum
for whichstd::is_error_code_enum<Enum>::value
istrue
.
-
-
To get a
result<T>
in Error capture state, initialize it with astd::shared_ptr<polymorphic_context>
(which can be obtained by calling e.g.make_shared_context
).
When a
result
object is initialized with astd::error_code
object, it is used to initialize anerror_id
object, then the behavior is the same as if initialized witherror_id
. -
- Throws:
-
-
Initializing the
result<T>
in Value state may throw, depending on which constructor ofT
is invoked; -
Other constructors do not throw.
-
A result that is in value state converts to true in boolean contexts. A result that is not in value state converts to false in boolean contexts.
|
result<T> objects are nothrow-moveable but are not copyable.
|
error
namespace boost { namespace leaf {
template <class... E>
<<unspecified-type>> result<T>::error() noexcept;
} }
Returns: A proxy object of unspecified type, implicitly convertible to any instance of the result
class template, as well as to error_id
.
-
If the proxy object is converted to some
result<U>
:-
If
*this
is in Value state, returnsresult<U>(error_id())
. -
Otherwise the state of
*this
is moved into the returnedresult<U>
.
-
-
If the proxy object is converted to an
error_id
:-
If
*this
is in Value state, returns a default-initializederror_id
object. -
If
*this
is in Error capture state, all captured error objects are loaded in the calling thread, and the capturederror_id
value is returned. -
If
*this
is in Error state, returns the storederror_id
.
-
-
If the proxy object is not used, the state of
*this
is not modified.
The returned proxy object refers to *this ; avoid holding on to it.
|
load
namespace boost { namespace leaf {
template <class T>
template <class... Item>
error_id result<T>::load( Item && ... item ) noexcept;
} }
This member function is designed for use in return
statements in functions that return result<T>
to forward additional error objects to the caller.
- Effects:
-
As if
error_id(this->error()).load(std::forward<Item>(item)…)
. - Returns:
-
*this
.
operator=
namespace boost { namespace leaf {
template <class T>
result<T> & result<T>::operator=( result && ) noexcept;
template <class T>
template <class U>
result<T> & result<T>::operator=( result<U> && ) noexcept;
} }
- Effects:
-
Destroys
*this
, then re-initializes it as if using the appropriateresult<T>
constructor. Basic exception-safety guarantee.
operator bool
namespace boost { namespace leaf {
template <class T>
result<T>::operator bool() const noexcept;
} }
- Returns:
-
If
*this
is in value state, returnstrue
, otherwise returnsfalse
.
value
, operator*
, ->
namespace boost { namespace leaf {
void result<void>::value() const; (1)
template <class T>
T const & result<T>::value() const; (2)
template <class T>
T & result<T>::value();
template <class T>
T const & result<T>::operator*() const; (2)
template <class T>
T & result<T>::operator*();
template <class T>
T const * result<T>::operator->() const; (2)
template <class T>
T * result<T>::operator->(); (2)
struct bad_result: std::exception { };
} }
1 | Only when T is void . |
2 | Only when T is not void . |
- Effects:
-
If
*this
is in value state, returns a reference (or pointer) to the stored value, otherwise throwsbad_result
.
verbose_diagnostic_info
namespace boost { namespace leaf {
class verbose_diagnostic_info: public error_info
{
//Constructors unspecified
friend std::ostream & operator<<( std::ostream & os, verbose_diagnostic_info const & x );
};
} }
Handlers passed to error handling functions such as try_handle_some
, try_handle_all
or try_catch
may take an argument of type verbose_diagnostic_info const &
if they need to print diagnostic information about the error.
The message printed by operator<<
includes the message printed by error_info
, followed by information about error objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active context
(these error objects were discarded by LEAF, because no handler needed them).
The additional information includes the types and the values of all such error objects.
The behavior of
|
Using verbose_diagnostic_info will likely allocate memory dynamically.
|
Reference: Predicates
The contents of each Reference section are organized alphabetically. |
A predicate is a special type of error handler argument which enables the handler selection procedure to consider the value of available error objects, not only their type; see Using Predicates to Handle Errors.
The following predicates are available:
In addition, any user-defined type Pred
for which is_predicate<Pred>::value
is true
is treated as a predicate. In this case, it is required that:
-
Pred
defines an accessible member typeerror_type
to specify the error object type it requires; -
Pred
defines an accessible static member functionevaluate
, which returns a boolean type, and can be invoked with an object of typeerror_type const &
; -
A
Pred
instance can be initialized with an object of typeerror_type
.
When an error handler takes an argument of a predicate type Pred
, the handler selection procedure drops the handler if an error object e
of type Pred::error_type
is not available. Otherwise, the handler is dropped if Pred::evaluate(e)
returns false
. If the handler is invoked, the Pred
argument is initialized with Pred{e}
.
Predicates are evaluated before the error handler is invoked, and so they may not access dynamic state (of course the error handler itself can access dynamic state, e.g. by means of lambda expression captures). |
enum class my_error { e1 = 1, e2, e3 };
struct my_pred
{
using error_type = my_error; (1)
static bool evaluate(my_error) noexcept; (2)
my_error matched; (3)
}
namespace boost { namespace leaf {
template <>
struct is_predicate<my_pred>: std::true_type
{
};
} }
1 | This predicate requires an error object of type my_error . |
2 | The handler selection procedure will call this function with an object e of type my_error to evaluate the predicate… |
3 | …and if successful, initialize the my_pred error handler argument with my_pred{e} . |
struct my_pred
{
using error_type = leaf::e_errno; (1)
static bool evaluate(leaf::e_errno const &) noexcept; (2)
leaf::e_errno const & matched; (3)
}
namespace boost { namespace leaf {
template <>
struct is_predicate<my_pred>: std::true_type
{
};
} }
1 | This predicate requires an error object of type e_errno . |
2 | The handler selection procedure will call this function with an object e of type e_errno to evaluate the predicate… |
3 | …and if successful, initialize the my_pred error handler argument with my_pred{e} . |
catch_
namespace boost { namespace leaf {
template <class... Ex>
struct catch_
{
std::exception const & matched;
// Other members not specified
};
template <class Ex>
struct catch_<Ex>
{
Ex const & matched;
// Other members not specified
};
template <class... Ex>
struct is_predicate<catch_<Ex...>>: std::true_type
{
};
} }
When an error handler takes an argument of type that is an instance of the catch_
template, the handler selection procedure first checks if a std::exception
was caught. If not, the handler is dropped. Otherwise, the handler is dropped if the caught std::exception
can not be dynamic_cast
to any of the specified types Ex…
.
If the error handler is invoked, the matched
member can be used to access the exception object.
See also: Using Predicates to Handle Errors. |
While catch_ requires that the caught exception object is of type that derives from std::exception , it is not required that the Ex… types derive from std::exception .
|
struct ex1: std::exception { };
struct ex2: std::exception { };
leaf::try_catch(
[]
{
return f(); // throws
},
[](leaf::catch_<ex1, ex2> c)
{ (1)
assert(dynamic_cast<ex1 const *>(&c.matched) || dynamic_cast<ex2 const *>(&c.matched));
....
} );
1 | The handler is selected if f throws an exception of type ex1 or ex2 . |
struct ex1: std::exception { };
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[](ex1 & e)
{ (1)
....
} );
1 | The handler is selected if f throws an exception of type ex1 . Notice that if we’re interested in only one exception type, as long as that type derives from std::exception , the use of catch_ is not required. |
if_not
namespace boost { namespace leaf {
template <class P>
struct if_not
{
<<deduced>> matched;
// Other members not specified
};
template <class P>
struct is_predicate<if_not<P>>: std::true_type
{
};
} }
When an error handler takes an argument of type if_not<P>
, where P
is another predicate type, the handler selection procedure first checks if an error object of the type E
required by P
is available. If not, the handler is dropped. Otherwise, the handler is dropped if P
evaluates to true
.
If the error handler is invoked, matched
can be used to access the matched object E
.
See also Using Predicates to Handle Errors. |
enum class my_enum { e1, e2, e3 };
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::if_not<leaf::match<my_enum, my_enum::e1, my_enum::e2>> )
{ (1)
....
} );
1 | The handler is selected if an object of type my_enum , which does not compare equal to e1 or to e2 , is associated with the detected error. |
match
namespace boost { namespace leaf {
template <class E, auto... V>
class match
{
<<deduced>> matched;
// Other members not specified
};
template <class E, auto... V>
struct is_predicate<match<E, V...>>: std::true_type
{
};
} }
When an error handler takes an argument of type match<E, V…>
, the handler selection procedure first checks if an error object e
of type E
is available. If it is not available, the handler is dropped. Otherwise, the handler is dropped if the following condition is not met:
p1 || p2 || … pn
.
Generally, pi
is equivalent to e == Vi
, except if Vi
is pointer to a function
bool (*Vi)(T x)
.
In this case it is required that Vi != 0
and that x
can be initialized with E const &
, and pi
is equivalent to:
Vi(e)
.
In particular, it is valid to pass pointer to the function leaf::category<Enum>
for any Vi
, where:
std::is_error_code_enum<Enum>::value || std::is_error_condition_enum<Enum>::value
.
In this case, pi
is equivalent to:
&e.category() == &std::error_code(Enum{}).category()
.
If the error handler is invoked, matched
can be used to access e
.
See also Using Predicates to Handle Errors. |
enum class my_enum { e1, e2, e3 };
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match<my_enum, my_enum::e1, my_enum::e2> m )
{ (1)
static_assert(std::is_same<my_enum, decltype(m.matched)>::value);
assert(m.matched == my_enum::e1 || m.matched == my_enum::e2);
....
} );
1 | The handler is selected if an object of type my_enum , which compares equal to e1 or to e2 , is associated with the detected error. |
enum class my_enum { e1=1, e2, e3 };
namespace std
{
template <> struct is_error_code_enum<my_enum>: std::true_type { };
}
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match<std::error_code, my_enum::e1, my_enum::e2> m )
{ (1)
static_assert(std::is_same<std::error_code const &, decltype(m.matched)>::value);
assert(m.matched == my_enum::e1 || m.matched == my_enum::e2);
....
} );
1 | The handler is selected if an object of type std::error_code , which compares equal to e1 or to e2 , is associated with the detected error. |
enum class enum_a { a1=1, a2, a3 };
enum class enum_b { b1=1, b2, b3 };
namespace std
{
template <> struct is_error_code_enum<enum_a>: std::true_type { };
template <> struct is_error_code_enum<enum_b>: std::true_type { };
}
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match<std::error_code, leaf::category<enum_a>, enum_b::b2> m )
{ (1)
static_assert(std::is_same<std::error_code const &, decltype(m.matched)>::value);
assert(&m.matched.category() == &std::error_code(enum_{}).category() || m.matched == enum_b::b2);
....
} );
1 | The handler is selected if an object of type std::error_code , which either has the same std::error_category as that of enum_a or compares equal to enum_b::b2 , is associated with the detected error. |
The use of the leaf::category
template requires automatic deduction of the type of each Vi
, which in turn requires C++17 or newer. The same applies to the use of std::error_code
as E
, but LEAF provides a compatible C++11 workaround for this case, using the template condition
. The following is equivalent to Example 2:
enum class my_enum { e1=1, e2, e3 };
namespace std
{
template <> struct is_error_code_enum<my_enum>: std::true_type { };
}
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match<leaf::condition<my_enum>, my_enum::e1, my_enum::e2> m )
{
static_assert(std::is_same<std::error_code const &, decltype(m.matched)>::value);
assert(m.matched == my_enum::e1 || m.matched == my_enum::e2);
....
} );
Instead of a set of values, the match
template can be given pointers to functions that implement a custom comparison. In the following example, we define a handler which will be selected to handle any error that communicates an object of the user-defined type severity
with value greater than 4:
struct severity { int value; }
template <int S>
constexpr bool severity_greater_than( severity const & e ) noexcept
{
return e.value > S;
}
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match<severity, severity_greater_than<4>> m )
{
static_assert(std::is_same<severity const &, decltype(m.matched)>::value);
assert(m.matched.value > 4);
....
} );
match_member
namespace boost { namespace leaf {
template <auto, auto... V>
struct match_member;
template <class E, class T, T E::* P, auto... V>
struct match_member<P, V...>
{
E const & matched;
// Other members not specified
};
template <auto P, auto... V>
struct is_predicate<match_member<P, V...>>: std::true_type
{
};
} }
This predicate is similar to match_value
, but able to bind any accessible data member of E
; e.g. match_member<&E::value, V…>
is equivalent to match_value<E, V…>
.
See also Using Predicates to Handle Errors. |
match_member requires at least C++17, whereas match_value does not.
|
match_value
namespace boost { namespace leaf {
template <class E, auto... V>
struct match_value
{
E const & matched;
// Other members not specified
};
template <class E, auto... V>
struct is_predicate<match_value<E, V...>>: std::true_type
{
};
} }
This predicate is similar to match
, but where match
compares the available error object e
of type E
to the specified values V…
, match_value
works with e.value
.
See also Using Predicates to Handle Errors. |
struct e_errno { int value; }
leaf::try_handle_some(
[]
{
return f(); // returns leaf::result<T>
},
[]( leaf::match_value<e_errno, ENOENT> m )
{ (1)
static_assert(std::is_same<e_errno const &, decltype(m.matched)>::value);
assert(m.matched.value == ENOENT);
....
} );
1 | The handler is selected if an object of type e_errno , with .value equal to ENOENT , is associated with the detected error. |
Reference: Traits
The contents of each Reference section are organized alphabetically. |
is_predicate
namespace boost { namespace leaf {
template <class T>
struct is_predicate: std::false_type
{
};
} }
The is_predicate
template is used by the handler selection procedure to detect predicate types. See Using Predicates to Handle Errors.
is_result_type
namespace boost { namespace leaf {
template <class R>
struct is_result_type: std::false_type
{
};
} }
The error handling functionality provided by try_handle_some
and try_handle_all
— including the ability to load error objects of arbitrary types — is compatible with any external result<T>
type R, as long as for a given object r
of type R
:
-
If
bool(r)
istrue
,r
indicates success, in which case it is valid to callr.value()
to recover theT
value. -
Otherwise
r
indicates a failure, in which case it is valid to callr.error()
. The returned value is used to initialize anerror_id
(note:error_id
can be initialized bystd::error_code
).
To use an external result<T>
type R, you must specialize the is_result_type
template so that is_result_type<R>::value
evaluates to true
.
Naturally, the provided leaf::result<T>
class template satisfies these requirements. In addition, it allows error objects to be transported across thread boundaries, using a std::shared_ptr<polymorphic_context>
.
Reference: Macros
The contents of each Reference section are organized alphabetically. |
BOOST_LEAF_ASSIGN
#define BOOST_LEAF_ASSIGN(v, r)\
auto && <<temp>> = r;\
if( !<<temp>> )\
return <<temp>>.error();\
v = std::forward<decltype(<<temp>>)>(<<temp>>).value()
BOOST_LEAF_ASSIGN
is useful when calling a function that returns result<T>
(other than result<void>
), if the desired behavior is to forward any errors to the caller verbatim.
In case of success, the result value()
of type T
is assigned to the specified variable v
, which must have been declared prior to invoking BOOST_LEAF_ASSIGN
. However, it is possible to use BOOST_LEAF_ASSIGN
to declare a new variable, by passing in v
its type together with its name, e.g. BOOST_LEAF_ASSIGN(auto && x, f())
calls f
, forwards errors to the caller, while capturing successful values in x
.
See also BOOST_LEAF_AUTO .
|
BOOST_LEAF_AUTO
#define BOOST_LEAF_AUTO(v, r)\
BOOST_LEAF_ASSIGN(auto v, r)
BOOST_LEAF_AUTO
is useful when calling a function that returns result<T>
(other than result<void>
), if the desired behavior is to forward any errors to the caller verbatim.
leaf::result<int> compute_value();
leaf::result<float> add_values()
{
BOOST_LEAF_AUTO(v1, compute_value()); (1)
BOOST_LEAF_AUTO(v2, compute_value()); (2)
return v1 + v2;
}
1 | Call compute_value , bail out on failure, define a local variable v1 on success. |
2 | Call compute_value again, bail out on failure, define a local variable v2 on success. |
Of course, we could write add_value
without using BOOST_LEAF_AUTO
. This is equivalent:
leaf::result<float> add_values() { auto v1 = compute_value(); if( !v1 ) return v1.error(); auto v2 = compute_value(); if( !v2 ) return v2.error(); return v1.value() + v2.value(); }
See also BOOST_LEAF_ASSIGN .
|
BOOST_LEAF_CHECK
#define BOOST_LEAF_CHECK(r)\
auto && <<temp>> = r;\
if( <<temp>> )\
;\
else\
return <<temp>>.error()
BOOST_LEAF_CHECK
is useful when calling a function that returns result<void>
, if the desired behavior is to forward any errors to the caller verbatim.
leaf::result<void> send_message( char const * msg );
leaf::result<int> compute_value();
leaf::result<int> say_hello_and_compute_value()
{
BOOST_LEAF_CHECK(send_message("Hello!")); (1)
return compute_value();
}
1 | Try to send a message, then compute a value, report errors using BOOST_LEAF_CHECK. |
Equivalent implementation without BOOST_LEAF_CHECK
:
leaf::result<float> add_values() { auto r = send_message("Hello!"); if( !r ) return r.error(); return compute_value(); }
BOOST_LEAF_EXCEPTION
#define BOOST_LEAF_EXCEPTION <<voodoo>>
- Effects:
-
BOOST_LEAF_EXCEPTION(e…)
is equivalent toleaf::exception(e…)
, except the current source location is automatically passed, in a
object (in addition to alle_source_location
e…
objects).
BOOST_LEAF_NEW_ERROR
#define BOOST_LEAF_NEW_ERROR <<voodoo>>
- Effects:
-
BOOST_LEAF_NEW_ERROR(e…)
is equivalent toleaf::new_error(e…)
, except the current source location is automatically passed, in a
object (in addition to alle_source_location
e…
objects).
BOOST_LEAF_THROW_EXCEPTION
#define BOOST_LEAF_THROW_EXCEPTION throw BOOST_LEAF_EXCEPTION
- Effects:
-
Throws the exception object returned by
BOOST_LEAF_EXCEPTION
.
Design
Rationale
- Definition:
-
Objects that carry information about error conditions are called error objects. For example, objects of type
std::error_code
are error objects.
The following reasoning is independent of the mechanism used to transport error objects, whether it is exception handling or anything else. |
- Definition:
-
Depending on their interaction with error objects, functions can be classified as follows:
-
Error initiating: functions that initiate error conditions by creating new error objects.
-
Error neutral: functions that forward to the caller error objects communicated by lower-level functions they call.
-
Error handling: functions that dispose of error objects they have received, recovering normal program operation.
-
A crucial observation is that error initiating functions are typically low-level functions that lack any context and can not determine, much less dictate, the correct program behavior in response to the errors they may initiate. Error conditions which (correctly) lead to termination in some programs may (correctly) be ignored in others; yet other programs may recover from them and resume normal operation.
The same reasoning applies to error neutral functions, but in this case there is the additional issue that the errors they need to communicate, in general, are initiated by functions multiple levels removed from them in the call chain, functions which usually are — and should be treated as — implementation details. An error neutral function should not be coupled with error object types communicated by error initiating functions, for the same reason it should not be coupled with any other aspect of their interface.
Finally, error handling functions, by definition, have the full context they need to deal with at least some, if not all, failures. In their scope it is an absolute necessity that the author knows exactly what information must be communicated by lower level functions in order to recover from each error condition. Specifically, none of this necessary information can be treated as implementation details; in this case, the coupling which is to be avoided in error neutral functions is in fact desirable.
We’re now ready to define our
- Design goals:
-
-
Error initiating functions should be able to communicate all information available to them that is relevant to the failure being reported.
-
Error neutral functions should not be coupled with error types communicated by lower-level error initiating functions. They should be able to augment any failure with additional relevant information available to them.
-
Error handling functions should be able to access all the information communicated by error initiating or error neutral functions that is needed in order to deal with failures.
-
The design goal that error neutral functions are not coupled with the static type of error objects that pass through them seems to require dynamic polymorphism and therefore dynamic memory allocations (the Boost Exception library meets this design goal at the cost of dynamic memory allocation).
As it turns out, dynamic memory allocation is not necessary due to the following
- Fact:
-
-
Error handling functions "know" which of the information error initiating and error neutral functions are able to communicate is actually needed in order to deal with failures in a particular program. Ideally, no resources should be used wasted storing or communicating information which is not currently needed to handle errors, even if it is relevant to the failure.
-
For example, if a library function is able to communicate an error code but the program does not need to know the exact error code, then that information may be ignored at the time the library function attempts to communicate it. On the other hand, if an error handling function needs that information, the memory needed to store it can be reserved statically in its scope.
The LEAF functions try_handle_some
, try_handle_all
and try_catch
implement this idea. Users provide error handling lambda functions, each taking arguments of the types it needs in order to recover from a particular error condition. LEAF simply provides the space needed to store these types (in the form of a std::tuple
, using automatic storage duration) until they are passed to a suitable handler.
At the time this space is reserved in the scope of an error handling function, thread_local
pointers of the required error types are set to point to the corresponding objects within it. Later on, error initiating or error neutral functions wanting to communicate an error object of a given type E
use the corresponding thread_local
pointer to detect if there is currently storage available for this type:
-
If the pointer is not null, storage is available and the object is moved into the pointed storage, exactly once — regardless of how many levels of function calls must unwind before an error handling function is reached.
-
If the pointer is null, storage is not available and the error object is discarded, since no error handling function makes any use of it in this program — saving resources.
This almost works, except we need to make sure that error handling functions are protected from accessing stale error objects stored in response to previous failures, which would be a serious logic error. To this end, each occurrence of an error is assigned a unique error_id
. Each of the E…
objects stored in error handling scopes is assigned an error_id
as well, permanently associating it with a particular failure.
Thus, to handle a failure we simply match the available error objects (associated with its unique error_id
) with the argument types required by each user-provided error handling function. In terms of C++ exception handling, it is as if we could write something like:
try
{
auto r = process_file();
//Success, use r:
....
}
catch(file_read_error &, e_file_name const & fn, e_errno const & err)
{
std::cerr <<
"Could not read " << fn << ", errno=" << err << std::endl;
}
catch(file_read_error &, e_errno const & err)
{
std::cerr <<
"File read error, errno=" << err << std::endl;
}
catch(file_read_error &)
{
std::cerr << "File read error!" << std::endl;
}
Of course this syntax is not valid, so LEAF uses lambda functions to express the same idea:
leaf::try_catch(
[]
{
auto r = process_file(); //Throws in case of failure, error objects stored inside the try_catch scope
//Success, use r:
....
}
[](file_read_error &, e_file_name const & fn, e_errno const & err)
{
std::cerr <<
"Could not read " << fn << ", errno=" << err << std::endl;
},
[](file_read_error &, e_errno const & err)
{
std::cerr <<
"File read error, errno=" << err << std::endl;
},
[](file_read_error &)
{
std::cerr << "File read error!" << std::endl;
} );
Similar syntax works without exception handling as well. Below is the same snippet, written using result<T>
:
return leaf::try_handle_some(
[]() -> leaf::result<void>
{
BOOST_LEAF_AUTO(r, process_file()); //In case of errors, error objects are stored inside the try_handle_some scope
//Success, use r:
....
return { };
}
[](leaf::match<error_enum, file_read_error>, e_file_name const & fn, e_errno const & err)
{
std::cerr <<
"Could not read " << fn << ", errno=" << err << std::endl;
},
[](leaf::match<error_enum, file_read_error>, e_errno const & err)
{
std::cerr <<
"File read error, errno=" << err << std::endl;
},
[](leaf::match<error_enum, file_read_error>)
{
std::cerr << "File read error!" << std::endl;
} );
result
| try_handle_some
| match
| e_file_name
| e_errno
Please post questions and feedback on the Boost Developers Mailing List. |
Critique 1: Error Types Do Not Participate in Function Signatures
A knee-jerk critique of the LEAF design is that it does not statically enforce that each possible error condition is recognized and handled by the program. One idea I’ve heard from multiple sources is to add E…
parameter pack to result<T>
, essentially turning it into expected<T,E…>
, so we could write something along these lines:
expected<T, E1, E2, E3> f() noexcept; (1)
expected<T, E1, E3> g() noexcept (2)
{
if( expected<T, E1, E2, E3> r = f() )
{
return r; //Success, return the T
}
else
{
return r.handle_error<E2>( [] ( .... ) (3)
{
....
} );
}
}
1 | f may only return error objects of type E1 , E2 , E3 . |
2 | g narrows that to only E1 and E3 . |
3 | Because g may only return error objects of type E1 and E3 , it uses handle_error to deal with E2 . In case r contains E1 or E3 , handle_error simply returns r , narrowing the error type parameter pack from E1, E2, E3 down to E1, E3 . If r contains an E2 , handle_error calls the supplied lambda, which is required to return one of E1 , E3 (or a valid T ). |
The motivation here is to help avoid bugs in functions that handle errors that pop out of g
: as long as the programmer deals with E1
and E3
, he can rest assured that no error is left unhandled.
Congratulations, we’ve just discovered exception specifications. The difference is that exception specifications, before being removed from C++, were enforced dynamically, while this idea is equivalent to statically-enforced exception specifications, like they are in Java.
Why not use the equivalent of exception specifications, even if they are enforced statically?
The short answer is that nobody knows how to fix exception specifications in any language, because the dynamic enforcement C++ chose has only different (not greater or fewer) problems than the static enforcement Java chose. … When you go down the Java path, people love exception specifications until they find themselves all too often encouraged, or even forced, to addthrows Exception
, which immediately renders the exception specification entirely meaningless. (Example: Imagine writing a Java generic that manipulates an arbitrary typeT
).[1]
Consider again the example above: assuming we don’t want important error-related information to be lost, values of type E1
and/or E3
must be able to encode any E2
value dynamically. But like Sutter points out, in generic contexts we don’t know what errors may result in calling a user-supplied function. The only way around that is to specify a single type (e.g. std::error_code
) that can communicate any and all errors, which ultimately defeats the idea of using static type checking to enforce correct error handling.
That said, in every program there are certain error handling functions (e.g. main
) which are required to handle any error, and it is highly desirable to be able to enforce this requirement at compile-time. In LEAF, the try_handle_all
function implements this idea: if the user fails to supply at least one handler that will match any error, the result is a compile error. This guarantees that the scope invoking try_handle_all
is prepared to recover from any failure.
Critique 2: LEAF Does Not Facilitate Mapping Between Different Error Types
Most C++ programs use multiple C and C++ libraries, and each library may provide its own system of error codes. But because it is difficult to define static interfaces that can communicate arbitrary error code types, a popular idea is to map each library-specific error code to a common program-wide enum.
For example, if we have —
namespace lib_a
{
enum error
{
ok,
ec1,
ec2,
....
};
}
namespace lib_b
{
enum error
{
ok,
ec1,
ec2,
....
};
}
— we could define:
namespace program
{
enum error
{
ok,
lib_a_ec1,
lib_a_ec2,
....
lib_b_ec1,
lib_b_ec2,
....
};
}
An error handling library could provide conversion API that uses the C++ static type system to automate the mapping between the different error enums. For example, it may define a class template result<T,E>
with value-or-error variant semantics, so that:
-
lib_a
errors are transported inresult<T,lib_a::error>
, -
lib_b
errors are transported inresult<T,lib_b::error>
, -
then both are automatically mapped to
result<T,program::error>
once control reaches the appropriate scope.
There are several problems with this idea:
-
It is prone to errors, both during the initial implementation as well as under maintenance.
-
It does not compose well. For example, if both of
lib_a
andlib_b
uselib_c
, errors that originate inlib_c
would be obfuscated by the different APIs exposed by each oflib_a
andlib_b
. -
It presumes that all errors in the program can be specified by exactly one error code, which is false.
To elaborate on the last point, consider a program that attempts to read a configuration file from three different locations: in case all of the attempts fail, it should communicate each of the failures. In theory result<T,E>
handles this case well:
struct attempted_location
{
std::string path;
error ec;
};
struct config_error
{
attempted_location current_dir, user_dir, app_dir;
};
result<config,config_error> read_config();
This looks nice, until we realize what the config_error
type means for the automatic mapping API we wanted to define: an enum
can not represent a struct
. It is a fact that we can not assume that all error conditions can be fully specified by an enum
; an error handling library must be able to transport arbitrary static types efficiently.
Critique 3: LEAF Does Not Treat Low Level Error Types as Implementation Details
This critique is a combination of Critique 1 and Critique 2, but it deserves special attention. Let’s consider this example using LEAF:
leaf::result<std::string> read_line( reader & r );
leaf::result<parsed_line> parse_line( std::string const & line );
leaf::result<parsed_line> read_and_parse_line( reader & r )
{
BOOST_LEAF_AUTO(line, read_line(r)); (1)
BOOST_LEAF_AUTO(parsed, parse_line(line)); (2)
return parsed;
}
1 | Read a line, forward errors to the caller. |
2 | Parse the line, forward errors to the caller. |
The objection is that LEAF will forward verbatim the errors that are detected in read_line
or parse_line
to the caller of read_and_parse_line
. The premise of this objection is that such low-level errors are implementation details and should be treated as such. Under this premise, read_and_parse_line
should act as a translator of sorts, in both directions:
-
When called, it should translate its own arguments to call
read_line
andparse_line
; -
If an error is detected, it should translate the errors from the error types returned by
read_line
andparse_line
to a higher-level type.
The motivation is to isolate the caller of read_and_parse_line
from its implementation details read_line
and parse_line
.
There are two possible ways to implement this translation:
1) read_and_parse_line
understands the semantics of all possible failures that may be reported by both read_line
and parse_line
, implementing a non-trivial mapping which both erases information that is considered not relevant to its caller, as well as encodes different semantics in the error it reports. In this case read_and_parse_line
assumes full responsibility for describing precisely what went wrong, using its own type specifically designed for the job.
2) read_and_parse_line
returns an error object that essentially indicates which of the two inner functions failed, and also transports the original error object without understanding its semantics and without any loss of information, wrapping it in a new error type.
The problem with 1) is that typically the caller of read_and_parse_line
is not going to handle the error, but it does need to forward it to its caller. In our attempt to protect the one error handling function from "implementation details", we’ve coupled the interface of all intermediate error neutral functions with the static types of errors they do not understand and do not handle.
Consider the case where read_line
communicates errno
in its errors. What is read_and_parse_line
supposed to do with e.g. EACCESS
? Turn it into READ_AND_PARSE_LINE_EACCESS
? To what end, other than to obfuscate the original (already complex and platform-specific) semantics of errno
?
And what if the call to read
is polymorphic, which is also typical? What if it involves a user-supplied function object? What kinds of errors does it return and why should read_and_parse_line
care?
Therefore, we’re left with 2). There’s almost nothing wrong with this option, since it passes any and all error-related information from lower level functions without any loss. However, using a wrapper type to grant (presumably dynamic) access to any lower-level error type it may be transporting is cumbersome and (like Niall Douglas explains) in general probably requires dynamic allocations. It is better to use independent error types that communicate the additional information not available in the original error object, while error handlers rely on LEAF to provide efficient access to any and all low-level error types, as needed.
Alternatives to LEAF
Below we offer a comparison of Boost LEAF to Boost Exception and to Boost Outcome.
Comparison to Boost Exception
While LEAF can be used without exception handling, in the use case when errors are communicated by throwing exceptions, it can be viewed as a better, more efficient alternative to Boost Exception. LEAF has the following advantages over Boost Exception:
-
LEAF does not allocate memory dynamically;
-
LEAF does not waste system resources communicating error objects not used by specific error handling functions;
-
LEAF does not store the error objects in the exception object, and therefore it is able to augment exceptions thrown by external libraries (Boost Exception can only augment exceptions of types that derive from
boost::exception
).
The following tables outline the differences between the two libraries which should be considered when code that uses Boost Exception is refactored to use LEAF instead.
It is possible to access Boost Exception error information using the LEAF error handling interface. See Boost Exception Integration. |
Boost Exception | LEAF |
---|---|
|
|
Boost Exception | LEAF |
---|---|
|
|
Boost Exception | LEAF |
---|---|
|
|
Boost Exception | LEAF |
---|---|
|
|
Boost Exception | LEAF |
---|---|
All supplied |
User-defined error objects are stored statically in the scope of |
Boost Exception | LEAF |
---|---|
|
Transporting error objects across thread boundaries requires the use of |
Boost Exception | LEAF |
---|---|
|
LEAF does not use |
The fact that Boost Exception stores all supplied If the user requires a complete diagnostic message, the solution is to use |
Comparison to Boost Outcome
Design Differences
Like LEAF, the Boost Outcome library is designed to work in low latency environments. It provides two class templates, result<>
and outcome<>
:
-
result<T,EC,NVP>
can be used as the return type innoexcept
functions which may fail, whereT
specifies the type of the return value in case of success, whileEC
is an "error code" type. Semantically,result<T,EC>
is similar tostd::variant<T,EC>
. Naturally,EC
defaults tostd::error_code
. -
outcome<T,EC,EP,NVP>
is similar toresult<>
, but in case of failure, in addition to the "error code" typeEC
it can hold a "pointer" object of typeEP
, which defaults tostd::exception_ptr
.
NVP is a policy type used to customize the behavior of .value() when the result<> or the outcome<> object contains an error.
|
The idea is to use result<>
to communicate failures which can be fully specified by an "error code", and outcome<>
to communicate failures that require additional information.
Another way to describe this design is that result<>
is used when it suffices to return an error object of some static type EC
, while outcome<>
can also transport a polymorphic error object, using the pointer type EP
.
In the default configuration of outcome<T> the additional information — or the additional polymorphic object — is an exception object held by std::exception_ptr . This targets the use case when an exception thrown by a lower-level library function needs to be transported through some intermediate contexts that are not exception-safe, to a higher-level context able to handle it. LEAF directly supports this use as well, see exception_to_result .
|
Similar reasoning drives the design of LEAF as well. The difference is that while both libraries recognize the need to transport "something else" in addition to an "error code", LEAF provides an efficient solution to this problem, while Outcome shifts this burden to the user.
The leaf::result<>
template deletes both EC
and EP
, which decouples it from the type of the error objects that are transported in case of a failure. This enables lower-level functions to freely communicate anything and everything they "know" about the failure: error code, even multiple error codes, file names, URLs, port numbers, etc. At the same time, the higher-level error handling functions control which of this information is needed in a specific client program and which is not. This is ideal, because:
-
Authors of lower-level library functions lack context to determine which of the information that is both relevant to the error and naturally available to them needs to be communicated in order for a particular client program to recover from that error;
-
Authors of higher-level error handling functions can easily and confidently make this determination, which they communicate naturally to LEAF, by simply writing the different error handlers. LEAF will transport the needed error objects while discarding the ones handlers don’t care to use, saving resources.
The LEAF examples include an adaptation of the program from the Boost Outcome result<> tutorial. You can view it on GitHub.
|
Programs using LEAF for error handling are not required to use leaf::result<T> ; for example, it is possible to use outcome::result<T> with LEAF.
|
The Interoperability Problem
The Boost Outcome documentation discusses the important problem of bringing together multiple libraries — each using its own error reporting mechanism — and incorporating them in a robust error handling infrastructure in a client program.
Users are advised that whenever possible they should use a common error handling system throughout their entire codebase, but because this is not practical, both the result<>
and the outcome<>
templates can carry user-defined "payloads".
The following analysis is from the Boost Outcome documentation:
If library A uses result<T, libraryA::failure_info>
, and library B uses result<T, libraryB::error_info>
and so on, there becomes a problem for the application writer who is bringing in these third party dependencies and tying them together into an application. As a general rule, each third party library author will not have built in explicit interoperation support for unknown other third party libraries. The problem therefore lands with the application writer.
The application writer has one of three choices:
-
In the application, the form of result used is
result<T, std::variant<E1, E2, …>>
whereE1, E2 …
are the failure types for every third party library in use in the application. This has the advantage of preserving the original information exactly, but comes with a certain amount of use inconvenience and maybe excessive coupling between high level layers and implementation detail. -
One can translate/map the third party’s failure type into the application’s failure type at the point of the failure exiting the third party library and entering the application. One might do this, say, with a C preprocessor macro wrapping every invocation of the third party API from the application. This approach may lose the original failure detail, or mis-map under certain circumstances if the mapping between the two systems is not one-one.
-
One can type erase the third party’s failure type into some application failure type, which can later be reconstituted if necessary. This is the cleanest solution with the least coupling issues and no problems with mis-mapping, but it almost certainly requires the use of
malloc
which the previous two did not.
The analysis above (emphasis added) is clear and precise, but LEAF and Boost Outcome tackle the interoperability problem differently:
-
The Boost Outcome design asserts that the "cleanest" solution based on type-erasure is suboptimal ("almost certainly requires the use of
malloc
"), and instead provides a system for injecting custom converters into theoutcome::convert
namespace, used to translate between library-specific and program-wide error types, even though this approach "may lose the original failure detail". -
The LEAF design asserts that coupling the signatures of error neutral functions with the static types of the error objects they need to forward to the caller does not scale, and instead transports error objects directly to error handling scopes where they are stored statically, effectively implementing the third choice outlined above (without the use of
malloc
).
Further, consider that Outcome aims to hopefully become the one error handling API all libraries would use, and in theory everyone would benefit from uniformity and standardization. But the reality is that this is wishful thinking. In fact, that reality is reflected in the design of outcome::result<>
, in its lack of commitment to using std::error_code
for its intended purpose: to be the standard type for transporting error codes. The fact is that std::error_code
became yet another error code type programmers need to understand and support.
In contrast, the design of LEAF acknowledges that C++ programmers don’t even agree on what a string is. If your project uses 10 different libraries, this probably means 15 different ways to report errors, sometimes across uncooperative interfaces (e.g. C APIs). LEAF helps you get the job done.
Benchmark
This benchmark compares the performance of LEAF, Boost Outcome and tl::expected
.
Running the Unit Tests
The unit tests can be run with Meson Build or with Boost Build. To run the unit tests:
Meson Build
Clone LEAF into any local directory and execute:
cd leaf
meson bld/debug
cd bld/debug
meson test
See meson_options.txt
found in the root directory for available build options.
Boost Build
Assuming the current working directory is <boostroot>/libs/leaf
:
../../b2 test
Configuration Macros
The following configuration macros are recognized:
-
BOOST_LEAF_DIAGNOSTICS
: Defining this macro to0
stubs out bothdiagnostic_info
andverbose_diagnostic_info
, which could improve the performance of the error path in some programs (if the macro is left undefined, LEAF defines it as1
). -
BOOST_LEAF_NO_EXCEPTIONS
: Disables all exception handling support. If left undefined, LEAF defines it based on the compiler configuration (e.g.-fno-exceptions
). -
BOOST_LEAF_NO_THREADS
: Disable all multi-thread support.
Limitations
LEAF requires C++11, including thread_local
support, except when compiled with BOOST_LEAF_NO_THREADS
(which can be useful on some embedded platforms).
When using dynamic linking, it is required that error types are declared with default
visibility, e.g.:
struct __attribute__ ((visibility ("default"))) my_error_info
{
int value;
};
This works as expected except on Windows, where thread-local storage is not shared between the individual binary modules. For this reason, to transport error objects across DLL boundaries, it is required that they’re captured in a polymorphic_context
, just like when Transporting Error Objects Between Threads.
When using dynamic linking, it is always best to define module interfaces in terms of C (and implement them in C++ if appropriate). |
Acknowledgements
Special thanks to Peter Dimov and Sorin Fetche.
Ivo Belchev, Sean Palmer, Jason King, Vinnie Falco, Glen Fernandes, Augustín Bergé — thanks for the valuable feedback.
Documentation rendered by Asciidoctor with these customizations.