Exploring Portable Error Handling in C++ with std::error_condition

2025-09-18

Think of std::error_condition as a portable, high-level error code. It's part of the C++ <system_error> header and is used to categorize errors based on their meaning, rather than their raw numeric value. This is different from std::error_code, which holds the low-level, system-specific error number (like errno on POSIX systems).

The key idea is that you can compare an std::error_code from one system to an std::error_condition that represents a standardized error meaning. This allows you to write code that checks for "permission denied" or "file not found" without knowing the specific integer value those errors have on every platform.

Here are some common problems developers run into when using std::error_condition and how to fix them.

This is the most frequent mistake. People often try to use std::error_condition to directly store an errno value.

Common Mistake

#include <system_error>
#include <iostream>

void do_something_wrong() {
    // This is not the right way to use it!
    std::error_condition err_cond(EPERM, std::generic_category());
    // EPERM is a low-level error code, not a high-level condition.
    // This will likely not work as expected.
}

Correct Approach

You should get the low-level std::error_code first and then compare it to the high-level std::error_condition. The == operator is overloaded to handle this comparison correctly.

#include <system_error>
#include <iostream>
#include <cerrno> // For EPERM

void handle_file_access() {
    // Let's pretend this function call failed and set errno.
    errno = EPERM;

    // 1. Get the low-level error_code from the system.
    std::error_code ec = std::make_error_code(std::errc::permission_denied);
    // Alternatively, from a system call: std::error_code ec(errno, std::system_category());

    // 2. Compare the error_code to the high-level error_condition.
    if (ec == std::errc::permission_denied) {
        std::cout << "Access denied! We can't do that here." << std::endl;
    } else {
        std::cout << "Some other error occurred." << std::endl;
    }
}

Explanation
std::errc::permission_denied is a standardized std::error_condition value. The magic happens with the == operator, which correctly checks if the std::error_code maps to that specific std::error_condition in its category.

If you're creating your own error system, you might want to define a custom category. A common mistake is not correctly implementing the virtual functions.

Common Mistake

#include <system_error>
#include <string>

// This is an incomplete implementation and will cause issues.
class MyErrorCategory : public std::error_category {
public:
    const char* name() const noexcept override {
        return "MyCategory";
    }

    std::string message(int ev) const override {
        // This is a minimal implementation, missing a lot of detail.
        return "An error in MyCategory";
    }
};

Correct Approach (with error_condition mapping)

The key is to implement the equivalent() function. This is what allows your custom std::error_code to be compared with a generic std::error_condition.

#include <system_error>
#include <string>
#include <iostream>

// Define our custom error category
class CustomCategory : public std::error_category {
public:
    const char* name() const noexcept override {
        return "CustomCategory";
    }

    std::string message(int ev) const override {
        // Map our specific integer values to a string message
        switch (static_cast<CustomError>(ev)) {
            case CustomError::InvalidInput: return "Invalid Input";
            case CustomError::ConnectionFailed: return "Connection Failed";
            default: return "Unknown custom error";
        }
    }

    // This is the crucial part for std::error_condition!
    bool equivalent(const std::error_code& code,
                    const std::error_condition& condition) const noexcept override {
        // Here we map our custom error codes to generic conditions
        if (condition == std::errc::invalid_argument &&
            code.value() == static_cast<int>(CustomError::InvalidInput)) {
            return true;
        }
        if (condition == std::errc::resource_unavailable_try_again &&
            code.value() == static_cast<int>(CustomError::ConnectionFailed)) {
            return true;
        }
        return false;
    }
};

// Define our custom error enumeration
enum class CustomError {
    InvalidInput = 1,
    ConnectionFailed = 2
};

const std::error_category& get_custom_category() {
    static CustomCategory instance;
    return instance;
}

std::error_code make_custom_error_code(CustomError e) {
    return std::error_code(static_cast<int>(e), get_custom_category());
}

int main() {
    std::error_code my_ec = make_custom_error_code(CustomError::InvalidInput);

    // Now, we can compare our custom error code to a standard condition!
    if (my_ec == std::errc::invalid_argument) {
        std::cout << "The error code maps to a generic 'invalid argument' condition." << std::endl;
    }
    
    return 0;
}

Explanation
The equivalent() function is the bridge. It lets you define the specific rules for how your custom std::error_code values map to the more general, portable std::error_condition values.


cpp



Mastering C++ std::unordered_multiset Hash Functions

First, let's quickly review what std::unordered_multiset::hash_function does. It's a member function that returns the hash function object used by the unordered_multiset


C++ Concurrency: A Guide to std::atomic and Its Pitfalls

Using std::atomic<std::shared_ptr> is a great way to handle thread-safe updates to a shared resource, but there are some classic traps developers fall into


static_cast vs. dynamic_cast: When to Use Each

static_cast is a C++ cast operator used for explicit type conversions that are checked at compile time. It's the most common cast you'll encounter and is used for things like converting a float to an int or a pointer to a derived class to a base class pointer



Understanding C++ Scoped Allocators: The Outer Allocator Explained

The std::scoped_allocator_adaptor is a special type of allocator that can be used to propagate a single allocator instance to multiple levels of nested containers


The noexcept Operator in C++: Common Issues and Modern Alternatives

The noexcept operator is a unary operator that checks if a given expression is guaranteed not to throw an exception. It evaluates to a bool constant true if the expression is noexcept


The C++20 std::chrono::operator<< for month_weekday: Pitfalls and Workarounds

The most frequent issue people run into with this function is its lack of universal support. It was introduced as part of the C++20 standard


Mastering C++ Threads: A Guide to std::jthread::joinable()

The std::jthread::joinable() method is a simple but important function in C++ concurrency. It's a boolean check that tells you whether a thread object is currently associated with an active thread of execution


Breaking the Rules: A Guide to the C++ 'friend' Mechanism

The C++ friend keyword is a mechanism that allows a function or an entire class to access the private and protected members of another class


std::strncmp: Common Issues and Modern C++ Alternatives

std::strncmp is a function from the C standard library that compares a specified number of characters from two C-style strings (character arrays). It's part of the <cstring> header and is often used for a quick


C++ Core Concepts: Troubleshooting Fundamental Types

C++ fundamental types are the building blocks of the language. They represent basic data like numbers, characters, and boolean values