Error Handling in C++: Abseil Status, StatusOr<T> & Go/Rust Comparison#

This article explains why large-scale C++ codebases favor value-based error handling (Errors as Values) over C++ exceptions (try-catch), how to use open-source Abseil (abseil-cpp) types absl::Status and absl::StatusOr<T>, and how this design maps directly to Go’s (T, error), Rust’s Result<T, E>, and C++23’s std::expected<T, E>.


1. Why Large-Scale C++ Projects Avoid Exceptions (try-catch)#

Although standard C++ supports throw and try-catch, many large production C++ codebases (following the Google C++ Style Guide) disable exceptions via -fno-exceptions and rely on explicit error return values.

Three Practical Limitations of C++ Exceptions#

  1. Invisible Control Flow at the Callsite:
    • Looking at int x = Compute(a) + Fetch(b);, it is impossible to tell from the callsite whether either function might throw an exception and abruptly unwind the call stack.
    • Because failure paths are not part of the function’s return type signature, reasoning about control flow during code reviews and refactoring becomes significantly harder.
  2. Fragile Exception Safety Across Large Codebases:
    • Unless every intermediate frame strictly adheres to RAII and strong exception safety guarantees, stack unwinding can leave objects with broken invariants or leaked resources.
    • Integrating exception-throwing code with legacy or third-party C++ libraries not written with exception safety in mind frequently leads to subtle bugs.
  3. Unwinding Overhead and Binary Size Cost:
    • While “zero-cost exceptions” optimize the non-throwing happy path, actually throwing an exception incurs thousands of CPU cycles traversing unwind tables (.eh_frame) and RTTI metadata, inflating both binary size and tail latency when errors occur.

The Alternative: Errors as Values: Instead of jumping up the call stack via throw, functions that can fail encode that possibility directly in their return type, forcing the caller to inspect and handle errors explicitly with compiler enforcement.


2. absl::Status: Representing Success or Error State#

When a function does not return a data payload and only needs to report whether an operation succeeded or why it failed (replacing bool or raw int error codes), it returns absl::Status from open-source Abseil.

  • Header: #include "absl/status/status.h"
  • Representation:
    • On success (OK): Represented as a single zero integer inlined without any heap allocation (effectively zero overhead).
    • On failure: Holds a canonical absl::StatusCode (aligned 1:1 with standard gRPC status codes), a human-readable error message, and optional structured payloads.
  • [[nodiscard]] Enforcement: absl::Status is annotated with [[nodiscard]], so ignoring a returned Status triggers a compiler warning or error.

Canonical absl::StatusCode Factory Functions#

Factory Function (absl/status/status.h)Corresponding absl::StatusCodeTypical Use Case
absl::OkStatus()StatusCode::kOk (0)Operation completed successfully
absl::InvalidArgumentError(msg)StatusCode::kInvalidArgumentCaller supplied an invalid argument (e.g., negative age, empty string)
absl::NotFoundError(msg)StatusCode::kNotFoundRequested file, key, or database record does not exist
absl::AlreadyExistsError(msg)StatusCode::kAlreadyExistsResource or key being created already exists
absl::PermissionDeniedError(msg)StatusCode::kPermissionDeniedCaller lacks authorization for the operation
absl::UnavailableError(msg)StatusCode::kUnavailableTransient network or service failure (often retryable)
absl::InternalError(msg)StatusCode::kInternalBroken internal system invariant or unexpected bug

Basic Usage of absl::Status#

#include <iostream>
#include "absl/status/status.h"
#include "absl/strings/string_view.h"

absl::Status ValidateUsername(absl::string_view username) {
  if (username.empty()) {
    return absl::InvalidArgumentError("Username cannot be empty");
  }
  if (username.size() > 32) {
    return absl::InvalidArgumentError("Username exceeds 32 characters");
  }
  return absl::OkStatus();
}

void HandleRegistration(absl::string_view username) {
  absl::Status status = ValidateUsername(username);
  if (!status.ok()) {
    std::cerr << "Validation failed [" << status.code() << "]: "
              << status.message() << "\n";
    return;
  }
  // Proceed with registration...
}

3. absl::StatusOr<T>: Holding Either a Value (T) or an Error (Status)#

When a function returns a result value T on success or an absl::Status error on failure, it returns absl::StatusOr<T>.

  • Header: #include "absl/status/statusor.h"
  • Core Concept (Tagged Union / Sum Type):
    • Holds either a valid value of type T or a non-OK absl::Status explaining why the value is absent (conceptually similar to std::variant<T, absl::Status>).
    • If ok() is true, a valid T is guaranteed to exist; if ok() is false, a non-OK absl::Status is guaranteed to exist. Ambiguous states (both present or both empty) are unrepresentable.

Why Prefer absl::StatusOr<T> Over Output Parameters (Status Func(T* out))?#

Historically, C++ codebases without exceptions used pointer output parameters (absl::Status Parse(string_view in, Data* out)) to return both a status and a value. absl::StatusOr<T> eliminates the drawbacks of output parameters:

AspectLegacy Output Parameter (Status Func(T* out))Modern Value Return (absl::StatusOr<T> Func())
Caller InitializationRequires default-constructing a dummy T out; beforehandWorks seamlessly with types that have no default constructor
Move-Only TypesAwkward to return std::unique_ptr<T>Cleanly returns ownership via absl::StatusOr<std::unique_ptr<Foo>>
Factory FunctionsConstructors cannot return errors, forcing two-phase Init()Enables static absl::StatusOr<Foo> Create(...) so partially initialized objects never exist
Copy/Move OptimizationSeparates declaration from populationIntegrates naturally with Copy Elision & Move Semantics

Using absl::StatusOr<T> Safely#

#include <memory>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"

struct UserProfile {
  int id;
  std::string name;
};

// Returns UserProfile on success, or an error absl::Status on failure
absl::StatusOr<UserProfile> FetchUserProfile(int user_id) {
  if (user_id <= 0) {
    // Returning an absl::Status implicitly converts it into a non-OK StatusOr<UserProfile>
    return absl::InvalidArgumentError("user_id must be positive");
  }
  if (user_id == 404) {
    return absl::NotFoundError(absl::StrCat("User ", user_id, " not found"));
  }

  // Returning a T (UserProfile) implicitly constructs an OK StatusOr<UserProfile>
  return UserProfile{.id = user_id, .name = "Alice"};
}

void ProcessUser(int user_id) {
  absl::StatusOr<UserProfile> result = FetchUserProfile(user_id);

  // 1. Always check ok() before accessing the value.
  if (!result.ok()) {
    // Extract the underlying absl::Status via result.status()
    absl::Status err = result.status();
    return;
  }

  // 2. Once ok() is verified, dereference with * or -> (or .value())
  int id = result->id;

  // 3. For heap-owning types (std::string, std::vector) or move-only types (std::unique_ptr),
  //    use std::move(*result) to move the value out without copying!
  UserProfile profile = std::move(*result);
}

Warning (Accessing the value when !ok()): Calling *result, result->, or result.value() when result.ok() is false terminates the process immediately (crash/abort). Always verify if (!result.ok()) before dereferencing.


4. Error Propagation Macros (RETURN_IF_ERROR & ASSIGN_OR_RETURN)#

When propagating errors up the call stack without custom recovery logic, writing four lines of if (!s.ok()) return s; after every call obscures the core business logic.

Across the open-source C++ ecosystem (Protobuf, TensorFlow, OpenXLA, MediaPipe, OR-Tools), two standard macro patterns, RETURN_IF_ERROR and ASSIGN_OR_RETURN, are used to keep error propagation concise.

1. Before vs. After Propagation Macros#

// ❌ Verbose manual error propagation
absl::StatusOr<OrderReceipt> PlaceOrderVerbose(int user_id, int item_id) {
  absl::Status auth_status = VerifyAuthToken(user_id);
  if (!auth_status.ok()) {
    return auth_status;
  }

  absl::StatusOr<UserProfile> user_or = FetchUserProfile(user_id);
  if (!user_or.ok()) {
    return user_or.status();
  }
  UserProfile user = std::move(*user_or);

  absl::StatusOr<InventoryItem> item_or = CheckInventory(item_id);
  if (!item_or.ok()) {
    return item_or.status();
  }
  InventoryItem item = std::move(*item_or);

  return CreateReceipt(user, item);
}

// ✅ Concise error propagation with RETURN_IF_ERROR and ASSIGN_OR_RETURN
absl::StatusOr<OrderReceipt> PlaceOrderClean(int user_id, int item_id) {
  RETURN_IF_ERROR(VerifyAuthToken(user_id));

  ASSIGN_OR_RETURN(UserProfile user, FetchUserProfile(user_id));
  ASSIGN_OR_RETURN(InventoryItem item, CheckInventory(item_id));

  return CreateReceipt(user, item);
}

2. How the Macros Expand Under the Hood#

A portable implementation compatible with absl/status looks like this:

// 1. RETURN_IF_ERROR(expr):
//    Evaluates expr; if the resulting absl::Status is not OK, returns it from the enclosing function.
#define RETURN_IF_ERROR(expr)                                \
  do {                                                       \
    if (const absl::Status _status = (expr); !_status.ok())  \
      return _status;                                        \
  } while (0)

// 2. ASSIGN_OR_RETURN(lhs, rexpr):
//    Evaluates rexpr (an absl::StatusOr<T>); if not OK, returns its status() from the enclosing
//    function. Otherwise, moves the contained value into lhs.
#define STATUS_MACROS_CONCAT_IMPL_(x, y) x##y
#define STATUS_MACROS_CONCAT_(x, y) STATUS_MACROS_CONCAT_IMPL_(x, y)

#define ASSIGN_OR_RETURN(lhs, rexpr)                                           \
  auto STATUS_MACROS_CONCAT_(_status_or_, __LINE__) = (rexpr);                 \
  if (!STATUS_MACROS_CONCAT_(_status_or_, __LINE__).ok()) {                    \
    return std::move(STATUS_MACROS_CONCAT_(_status_or_, __LINE__)).status();   \
  }                                                                            \
  lhs = *std::move(STATUS_MACROS_CONCAT_(_status_or_, __LINE__))

Why must ASSIGN_OR_RETURN be a macro rather than a regular C++ function? It must perform two actions in the caller’s frame: (1) execute an early return from the enclosing function (PlaceOrderClean) on error, and (2) introduce a new local variable (UserProfile user) into the enclosing scope on success. In C++, only preprocessor macros can both inject a return statement into the caller and declare a variable in the caller’s scope.


5. Comparing C++ (StatusOr / std::expected), Go, and Rust#

The “Errors as Values” philosophy behind absl::StatusOr<T> shares the exact same conceptual foundation as Go, Rust, and C++23’s std::expected<T, E>.

1. Side-by-Side Comparison Matrix#

DimensionC++ Abseil (absl::StatusOr<T>)C++23 Standard (std::expected<T, E>)Go ((T, error))Rust (Result<T, E>)
Type StructureSum Type (holds either T or absl::Status)Sum Type (holds either T or arbitrary error type E)Product Type / Multi-Return (zero-value of T and error coexist)Algebraic Data Type (enum) (Ok(T) or Err(E))
Status-Only Returnabsl::Statusstd::expected<void, E>errorResult<(), E>
Value ExtractionCheck if (r.ok()), then *r / std::move(*r)Check if (r.has_value()), then *r / std::move(*r)Check if err == nil, then read vmatch, if let, or postfix ? operator
Error PropagationRETURN_IF_ERROR(expr) / ASSIGN_OR_RETURN(v, expr) (macros)Manual if (!r) return std::unexpected(r.error());Explicit if err != nil { return zero, err }expr? (built-in postfix language operator)
Preventing Ignored Errors[[nodiscard]] compiler warning/error[[nodiscard]] supportUnused variable compiler error unless explicitly discarded with _#[must_use] warning + impossible to read T without unwrapping the enum

2. Key Architectural Differences#

  1. Go (T, error) vs. absl::StatusOr<T> / Rust Result<T, E> (Product Type vs. Sum Type):
    • Go returns a tuple (T, error). Even when an error occurs, the first element (T) must still be constructed as its zero value (0, "", nil). Moreover, if a programmer forgets if err != nil, nothing in the type system prevents reading the invalid zero value v.
    • absl::StatusOr<T> and Rust Result<T, E> are disjoint sum types. When an error is returned, T is never constructed at all (requiring no default constructor), and the value is encapsulated inside the wrapper until .ok() or pattern matching is performed.
  2. Rust’s ? Operator vs. C++’s ASSIGN_OR_RETURN:
    • Rust provides first-class language syntax (?): let user = fetch_user(id)?; unwraps Ok(T) into user or immediately returns Err(e) from the enclosing function.
    • Because C++ lacks a built-in postfix propagation operator, ASSIGN_OR_RETURN(UserProfile user, FetchUserProfile(id)); serves as the direct C++ equivalent of Rust’s let user = fetch_user(id)?;.
  3. absl::StatusOr<T> vs. C++23 std::expected<T, E>:
    • The design of absl::StatusOr<T> heavily inspired C++23’s <expected> (std::expected<T, E>).
    • While std::expected<T, E> parameterizes the error type E, absl::StatusOr<T> intentionally standardizes the error type on absl::Status. This allows errors to propagate across module and library boundaries seamlessly without requiring manual error-type conversion glue at every layer.

3. The Exact Same Function in All Four Models#

// [1] C++ (Open-Source Abseil: absl::StatusOr<T>)
absl::StatusOr<int> ReadUserAge(int id) {
  ASSIGN_OR_RETURN(std::string raw_json, FetchUserJson(id));
  ASSIGN_OR_RETURN(int age, ParseAgeField(raw_json));
  RETURN_IF_ERROR(ValidateAgeRange(age));
  return age;
}
// [2] C++23 Standard (<expected>: std::expected<T, E>)
#include <expected>
#include <string>

std::expected<int, std::string> ReadUserAge(int id) {
  auto raw_json = FetchUserJson(id);
  if (!raw_json) return std::unexpected(raw_json.error());

  auto age = ParseAgeField(*raw_json);
  if (!age) return std::unexpected(age.error());

  if (auto valid = ValidateAgeRange(*age); !valid) {
    return std::unexpected(valid.error());
  }
  return *age;
}
// [3] Go: (T, error) multi-return + if err != nil
func ReadUserAge(id int) (int, error) {
    rawJSON, err := FetchUserJSON(id)
    if err != nil {
        return 0, err
    }
    age, err := ParseAgeField(rawJSON)
    if err != nil {
        return 0, err
    }
    if err := ValidateAgeRange(age); err != nil {
        return 0, err
    }
    return age, nil
}
// [4] Rust: Result<T, E> + ? operator
fn read_user_age(id: i32) -> Result<i32, AppError> {
    let raw_json = fetch_user_json(id)?;
    let age = parse_age_field(&raw_json)?;
    validate_age_range(age)?;
    Ok(age)
}