Use cases for std::error_code

I was wondering about that a while back myself and found the answer here. Essentially, error_code is used to store and transport error codes, while error_condition is used to match error codes.

void handle_error(error_code code) {
   if     (code == error_condition1) do_something();
   else if(code == error_condition2) do_something_else();
   else                              do_yet_another_thing();
}

Each error_condition is equivalent to a set of error_code, possibly from different error_categories. This way you can treat all errors of a certain type the same, no matter which subsystem they originate from.

error_code on the other hand contains exactly the category of the subsystem it originated from. This is useful for debugging and when reporting the error: you may be interested to know whether a “permission denied” error was because of insufficient access rights on the local file system or because of a 403 error that your http-downloader-library received, and may want to put that detail in the error message, but your program has to abort either way.

What constitutes equivalence is defined by the categories; if the error_code‘s category considers the error_condition equivalent, or the error_condition‘s category considers the error_code equivalent, then operator== returns true for that pair of error_condition and error_code. That way you can have error_codes from your own error category and make them equivalent to certain generic or system error_conditions.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)