Search code examples
c++c++11std-system-error

Is std::error_code a good way to issue warnings?


I'm currently using std::error_code to give feedback to the users of my API when something goes wrong. Would it be semantically acceptable to add an std::error_condition of type warning to notify my users that there was a minor issue but that operations will continue? Or should I only use logging for this?


Solution

  • If I got it correctly, you're asking if returning a warning should be considered abusing std::error_code semantics or not.

    Now, the standard introduces error_code as part of the standard diagnostics library

    [diagnostics.general] This Clause describes components that C++ programs may use to detect and report error conditions.

    and, as far as I know, poses no semantical requirements on what an "error condition" is, we can just assume that these are to be used to report that something went wrong, but it does not seem imposing what the effects of a partial fulfillment of an operation specification should be, the operation should tell you.

    The only semantical requirement I see, is that error_code (and error_condition) is boolean convertible, that is, a 'zero' error code should always mean success.

    Now, given that you supposedly want an operation completing with a warning to be considered successful, for this reason I would not consider valid to return such a warning via an error code; that said, you may always let your operation return two error codes (in the way you like, maybe belonging to different categories), documenting that only the first one reports the fulfillment of the operation effects:

    auto [err,war] = some_operation();
    
    if(err) call_the police(); // some_operation failed
    else if(war) // some_operation complains
    {
      std::cerr << "hold breath...";
    
      if( war == some_error_condition )
        thats_unacceptable();
    
      //else ignore
    }
    

    That said, note that there exist real use cases deviating from my reasoning above; indeed, things like HTTP result codes and libraries (like Vulkan) do use non zero 'result codes' for successful or partially successful conditions ...

    moreover, here one of the very authors of the diagnostic library both claims that "the facility uses a convention where zero means success." and at the same time uses error_code to model HTTP errors (200status code included).

    This sheds some doubts either on the actual semantics of error_code::operator bool() (the meaning of which is not explicitly laid out in the standard) or on the effective ability of the standard diagnostic library to model the error code concept in a general way. YMMV.