You have to come up with error code and category in order to create error_code
object. Here is an example, assuming that error is due to another host refusing connection:
error_code ec (errc::connection_refused, system_category());
return ec;
You can also pass errno
value as error code when using system category. For example:
#include <fstream>
#include <cerrno>
#include <boost/system/system_error.hpp>
void foo ()
{
ifstream file ("test.txt");
if (!file.is_open ())
{
int err_code = errno;
boost::system::error_code ec (err_code
, boost::system::system_category ());
throw boost::system::system_error (ec, "cannot open file");
}
}
Unfortunately, this library is poorly documented, so I can recommend you to look into header files to figure things out. The code is fairly simple and straight forward there.
Just in case your compiler supports C++11 and you are willing to use it, this functionality made it into standard. As far as I know gcc 4.6.1 has it already. Here is a simple example:
#include <cerrno>
#include <system_error>
std::error_code
SystemError::getLastError ()
{
int err_code = errno;
return std::error_code (err_code, std::system_category ());
}
void foo ()
{
throw std::system_error (getLastError (), "something went wrong");
}
Generally, libraries pass error_code
object around if there is no need to throw and use system_error
to throw an exception describing system failures. Another reason to use error_code
without exceptions is when you need to signal the error across different threads. But C++11 has a solution for propagating exceptions across threads.
Hope it helps!