Search code examples
c++c++11

How do I test that an std::error_code is not an error?


I have a method that returns an std::error_code. I am not particularly interested in the error message, only in whether or not the method succeeded.

What is the best way to test that an std::error_code represents a successful operation?


Solution

  • I came across the similar situation when working with the ASIO library. As what one of their blog posts suggests, std::error_code is meant to be tested as follows:

    std::error_code ec;
    // ...    
    if (!ec)
    {
      // Success.
    }
    else
    {
      // Failure.
    }
    

    Having dug a little deeper, I found this (much more recent) discussion in the C++ Standard Google group, which confirms the statement above but also raises questions about whether the current design of std::error_code is straightforward enough.

    Long story short, if you need to simply tell errors from success, !static_cast<bool>(errorCode) is what you need.