Canonical Error Codes in Abseil Status: The Complete Guide to absl::StatusCode
Abseil's absl::Status class uses a fixed set of 17 canonical error codes defined in absl/status/status.h that mirror Google RPC status codes, providing a stable, cross-library vocabulary for error handling in C++.
The abseil/abseil-cpp library provides the foundational absl::Status class for error propagation, which relies on a standardized enumeration of canonical error codes. These codes establish a consistent language for describing failure modes across all Abseil-based libraries and applications, ensuring interoperability and clear error semantics.
The Complete List of Canonical Abseil Status Codes
The absl::StatusCode enumeration in absl/status/status.h defines 17 canonical error codes. These values are intentionally stable and align with the Google RPC status code specification:
kOk— Operation completed successfully.kCancelled— Operation was cancelled, typically by the caller.kUnknown— Unknown error; a catch-all for unexpected failures not matching other codes.kInvalidArgument— Bad input arguments supplied to the function.kDeadlineExceeded— Requested operation timed out before completion.kNotFound— Requested entity (file, record, etc.) does not exist.kAlreadyExists— Attempt to create something that already exists.kPermissionDenied— Caller does not have the required permission.kUnauthenticated— Authentication required but missing or invalid.kResourceExhausted— Resource limits (memory, quota, rate) have been reached.kFailedPrecondition— System is not in a state required for the operation.kAborted— Operation aborted, typically due to a concurrency conflict.kOutOfRange— Index or offset outside the valid range.kUnimplemented— Feature or operation not implemented or supported.kInternal— Internal error, usually indicating a bug in the service.kUnavailable— Service is currently unavailable (overloaded or down).kDataLoss— Irrecoverable data loss or corruption.
These codes form a canonical set, meaning they are deliberately limited and stable. Code that checks for specific StatusCode values can rely on backward compatibility across library versions.
Core Implementation in absl/status/status.h
The canonical error codes are defined in absl/status/status.h, which implements the absl::Status class and the absl::StatusCode enum. This header also provides helper factory functions for constructing status objects with specific codes:
absl::OkStatus()— Returns a status withkOk.absl::CancelledError(const std::string& message)— Returns a status withkCancelled.absl::NotFoundError(const std::string& message)— Returns a status withkNotFound.- Similar constructors exist for other error codes (e.g.,
absl::InvalidArgumentError,absl::InternalError).
The implementation ensures that error messages are stored efficiently alongside the canonical code, allowing rich error context without sacrificing performance.
Practical Usage Patterns
Constructing Status Objects
Functions should return absl::Status to signal success or failure using the canonical codes. In absl/status/status.h, the factory functions simplify creating these objects:
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
absl::Status ReadFile(const std::string& path) {
if (!std::filesystem::exists(path)) {
return absl::NotFoundError(absl::StrCat("File not found: ", path));
}
// ... read the file ...
return absl::OkStatus(); // kOk
}
Propagating and Checking Codes
When calling functions that return absl::Status, propagate errors immediately or check specific canonical codes to handle specific failure modes:
absl::Status ProcessData() {
if (auto s = ReadFile("config.txt"); !s.ok()) {
// Preserve the original canonical code and message
return s;
}
// ... continue processing ...
return absl::OkStatus();
}
// Checking a specific canonical code
absl::Status s = ProcessData();
if (s.code() == absl::StatusCode::kNotFound) {
// Handle missing-file scenario specially
}
Integration with StatusOr and Macros
Beyond absl::Status, the canonical error codes integrate with related Abseil components:
absl/status/statusor.h— Providesabsl::StatusOr<T>, which holds either a value of typeTor anabsl::Status. It uses the same canonical codes for error states.absl/status/status_macros.h— Defines convenience macros likeABSL_RETURN_IF_ERRORandABSL_ASSIGN_OR_RETURNthat work with the canonical error codes to reduce boilerplate.absl/status/status_matchers.h— Offers GoogleTest matchers for asserting onabsl::Statusvalues in unit tests, verifying specific canonical codes.
This ecosystem ensures that the canonical error codes remain the single source of truth for error semantics across Abseil-based projects.
Summary
- Abseil defines 17 canonical error codes in
absl/status/status.hthat map to standard RPC status codes. - The
absl::StatusCodeenum includes values likekNotFound,kInvalidArgument, andkInternal, providing a stable vocabulary for errors. - Helper functions such as
absl::NotFoundError()andabsl::OkStatus()simplify constructing status objects. - Integration with
absl::StatusOrand status macros ensures consistent error handling patterns across libraries.
Frequently Asked Questions
What is the difference between kUnknown and kInternal?
kUnknown is a catch-all for errors that do not fit any other canonical category, often used when the error originates from an external system that uses a different error taxonomy. kInternal specifically indicates an internal logic error or bug within the service itself, such as an invariant violation or unexpected null pointer.
How do I create a custom error message with a canonical code?
Use the factory functions provided in absl/status/status.h. For example, absl::InvalidArgumentError("negative size") creates a status with code kInvalidArgument and your custom message. These functions combine the canonical code with a descriptive string without requiring manual enum construction.
Are Abseil Status codes compatible with gRPC status codes?
Yes. The canonical error codes in absl::StatusCode are designed to mirror the Google RPC status codes used by gRPC and other Google APIs. This alignment allows for seamless translation between absl::Status and gRPC status objects when building networked services.
Where should I use absl::Status versus absl::StatusOr?
Use absl::Status for functions that perform operations without returning a value on success (e.g., WriteFile), where kOk indicates success. Use absl::StatusOr<T> for functions that return a value on success (e.g., ReadFile returning file contents), where the object either contains the value T or an error status with one of the canonical codes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →