pw_status#
Exception-free error propagation for embedded
Stable C++ C Python Java TypeScript Rust
Easy: Simple to understand, includes convenient macro PW_TRY
Efficient: No memory allocation, no exceptions
Established: Just like
absl::Status, deployed extensively at GoogleCustomizable: Create custom status types for domain-specific error codes with pw_enum
pw::Status is Pigweed’s error propagation primitive, enabling
exception-free error handling. The primary feature of pw_status is the
pw::Status class, a simple, zero-overhead status object that
wraps a status code, and the PW_TRY macro. For example:
#include "pw_log/log.h"
#include "pw_log/status.h"
#include "pw_status/status.h"
pw::Status ImuEnable() {
if (!device_has_imu) {
return Status::FailedPrecondition();
}
PW_TRY(ImuSpiSendEnable()); // Propagates failure on non-OK status.
return pw::OkStatus();
}
void Initialize() {
if (auto status = ImuEnable(); status.ok()) {
PW_LOG_INFO("Imu initialized successfully");
} else {
if (status.IsFailedPrecondition()) {
PW_LOG_WARN("No IMU present");
} else {
// Logs the status by name, e.g. "IMU init failed: UNAVAILABLE".
PW_LOG_ERROR("IMU init failed: " PW_STATUS_FMT, PW_LOG_STATUS(status));
}
}
}
pw_status provides an implementation of status in every supported
Pigweed language, including C, Rust, TypeScript, Java, and Python.
Pigweed’s status matches Google’s standard status codes (see the Google APIs repository). These codes are used extensively in Google projects including Abseil (status/status.h) and gRPC (doc/statuscodes.md).
Integrate pw_status into your project, see common uses
Detailed description of pw_status’s methods.
Quick reference#
See Status codes for the precise semantics of each error, as well as how to spell the status in each of our supported languages. Click on the status names below to jump directly to that error’s reference.
Status |
Code |
Description |
|---|---|---|
0 |
Operation succeeded |
|
1 |
Operation was cancelled, typically by the caller |
|
2 |
Unknown error occurred. Avoid this code when possible. |
|
3 |
Argument was malformed; e.g. invalid characters when parsing integer |
|
4 |
Deadline passed before operation completed |
|
5 |
The entity that the caller requested (e.g. file or directory) is not found |
|
6 |
The entity that the caller requested to create is already present |
|
7 |
Caller lacks permission to execute action |
|
8 |
Insufficient resources to complete operation; e.g. supplied buffer is too small |
|
9 |
System isn’t in the required state; e.g. deleting a non-empty directory |
|
10 |
Operation aborted due to e.g. concurrency issue or failed transaction |
|
11 |
Operation attempted out of range; e.g. seeking past end of file |
|
12 |
Operation isn’t implemented or supported |
|
13 |
Internal error occurred; e.g. system invariants were violated |
|
14 |
Requested operation can’t finish now, but may at a later time |
|
15 |
Unrecoverable data loss occurred while completing the requested operation |
|
16 |
Caller does not have valid authentication credentials for the operation |
Logging statuses#
To log a status, describe what failed, then log the status with
PW_STATUS_FMT and PW_LOG_STATUS from pw_log/status.h
(//pw_log:status):
pw::Status ReadSector(int sector) {
if (sector < 0) {
return pw::Status::InvalidArgument(
PW_STATUS_MSG("Sector cannot be negative"));
}
if (sector >= kSectorCount) {
return pw::Status::OutOfRange();
}
return pw::OkStatus();
}
void LoadSector(int sector) {
if (pw::Status status = ReadSector(sector); !status.ok()) {
// Describe what failed, then log the status with PW_STATUS_FMT and
// PW_LOG_STATUS.
PW_LOG_ERROR("Read failed: " PW_STATUS_FMT, PW_LOG_STATUS(status));
}
}
The status is logged by name. If it has a message, the message follows in parentheses:
Read failed: OUT_OF_RANGE
Read failed: INVALID_ARGUMENT (Sector cannot be negative)
Messages are only logged if the project enables them. Otherwise, the second line is
Read failed: INVALID_ARGUMENT.
Write logs as
"<what failed>: " PW_STATUS_FMT. The status needs no other punctuation. The parentheses show where a message ends, so the status can also be followed by more text.Results:
PW_LOG_STATUSalso accepts a pw::Result or pw::StatusWithSize. Pass the object itself (PW_LOG_STATUS(result)).Custom statuses: Statuses generated by
pw_enumhave their own format macro to use in place ofPW_STATUS_FMT, such asMY_DRIVER_I2C_STATUS_FMT. See logging pw_enum statuses.Code only: To log the code and never the message, use PW_STATUS_CODE_FMT with PW_LOG_ENUM.
Tokenized logs: With a tokenizing
pw_logbackend, the status code and message are logged as tokens instead of strings. See PW_LOG_STATUS details.
Custom status codes with StatusBase#
pw::StatusBase is a base class template that provides Pigweed status
semantics for custom code types, such as domain-specific error enums or integer
codes. It provides ok() checks, [[nodiscard]] enforcement, and error
propagation with PW_TRY and pw::Result. Pigweed’s standard
pw::Status is itself implemented as a concrete class inheriting from
StatusBase<Status, PW_STATUS_OK>.
Each StatusBase specialization designates one code value as success (ok()
== true). Custom status types are constructed from a status code (e.g.
MyStatus(MyStatus::Code::kFailed)). They default construct to the OK code.
The underlying code type is aliased as MyStatus::Code.
Enum status codes#
Enums are recommended for custom status codes because they prevent arbitrary or
unknown values and allow the compiler to warn about unhandled cases in
switch statements.
The recommended way to define an enum-based status type is with
pw_enum’s PW_ENUM_STATUS macro (see
Defining custom status types). PW_ENUM_STATUS generates a
StatusBase-derived class from an enum, complete with a factory function for
each error code, Is*() query functions, stringification, and tokenized
logging support.
If not using pw_enum, pw::StatusOf (guide) is a final, [[nodiscard]]
status class template that wraps an existing enum:
enum class DriverError : uint8_t {
kOk,
kBusFault,
kTimeout,
};
using DriverStatus = pw::StatusOf<DriverError::kOk>;
constexpr DriverStatus WriteByte(uint8_t byte) {
if (byte == 0xFF) {
return DriverStatus(DriverError::kBusFault);
}
return DriverStatus();
}
// Propagate custom errors using PW_TRY.
constexpr DriverStatus SendPacket(uint8_t header, uint8_t payload) {
PW_TRY(WriteByte(header));
PW_TRY(WriteByte(payload));
return DriverStatus();
}
Callers inspect the status or compare it directly against the underlying enum:
DriverStatus status = SendPacket(0x01, 0x02);
if (status.ok()) {
// Packet sent successfully.
} else if (status == DriverError::kBusFault) {
// Handle bus fault.
}
To fully customize the status class, subclass StatusBase directly.
Non-enum status codes#
Enums are recommended for status codes because they prevent arbitrary or unknown
values and allow the compiler to warn about unhandled cases in switch
statements. However, StatusBase also supports non-enum types such as
integers when interfacing with existing protocols or numeric error codes. For
example, HTTP status codes can be represented with 200 designating success:
// StatusBase can also be used with non-enum types such as integers.
class [[nodiscard]] HttpStatus final : public pw::StatusBase<HttpStatus, 200> {
public:
constexpr HttpStatus() = default;
explicit constexpr HttpStatus(int code) : StatusBase(code) {}
};
constexpr HttpStatus FetchResource(bool resource_found) {
if (!resource_found) {
return HttpStatus(404); // Explicit construction for non-OK codes
}
return HttpStatus(); // Defaults to 200 OK
}
Callers handle non-enum statuses in the same way:
HttpStatus status = FetchResource(true);
if (status.ok()) {
// Request succeeded (200).
} else {
// Handle HTTP error code (e.g. status.code() == 404).
}
Status messages#
pw::Status and other StatusBase-derived statuses can carry an
optional error message alongside their status code. Messages add context to an
error without adding codes (e.g. which argument was invalid).
To attach a message, include pw_status/message.h (//pw_status:message)
and pass a PW_STATUS_MSG to a factory function or constructor:
pw::Status ReadSector(int sector) {
if (sector < 0) {
return pw::Status::InvalidArgument(
PW_STATUS_MSG("Sector cannot be negative"));
}
return pw::OkStatus();
}
When the status is logged, its message follows its code in parentheses:
Read failed: INVALID_ARGUMENT (Sector cannot be negative)
Write messages as short phrases without a period at the end. Say what the status code cannot, rather than repeating it.
PW_STATUS_MSGonly accepts string literals.Messages are only stored for non-OK statuses.
has_message()reports whether a status has a message.message()returns the message, which can be passed to another status of the same type to change the code and keep the message.A message with no text (
PW_STATUS_MSG("")) is still a message. It logs asCODE ().Unlike
absl::Status, equality comparisons (==and!=) consider only the status code and ignore messages, so attaching a message or changing PW_STATUS_CFG_MESSAGES never changes comparison results.Update(), PW_TRY, and pw::Result carry the message along with the code. pw::StatusWithSize does not have room for a message.Creating a status with a message is
constexprin C++23 and later, and is neverconstexprin earlier standards.
Which statuses support messages#
A status type supports messages if its code is an enum registered with PW_ENUM whose values are all from 0 to 65535. This includes pw::Status and most statuses generated by PW_ENUM_STATUS.
Passing a PW_STATUS_MSG to any other status type is a compile error,
whether or not messages are enabled. This applies to statuses with integer
codes, with enums that are not registered with PW_ENUM, and with enums that
have negative or larger values. It also applies to status types that opt out of
messages, such as those that represent a state rather than an error:
using CompactStatus = pw::StatusOf<Code::kOk, pw::StatusMessages::kDisabled>;
Enabling messages#
Messages are disabled by default. PW_STATUS_MSG arguments are then
discarded at compile time, and every status is exactly as large as its code, so
messages can be added to code freely.
Set the PW_STATUS_CFG_MESSAGES module configuration option to store messages. Messages are stored in the form the pw_log backend emits, so choose the value that matches the backend:
PW_STATUS_CFG_MESSAGES_TOKENIZED, for backends that tokenize logs (e.g.
pw_log_tokenized): The string is tokenized with pw_tokenizer. The status is one 32-bit word: the code in as many low bits as the enum’s values need (5 forpw::Status), and the message’s token in the rest. Checkingok()is unchanged and reading the code costs one mask. The word is logged as is, as a bit field token.Each status code enum has its own token domain for messages, since message tokens are masked to fit the bits its code leaves free. The domain is the code enum’s domain followed by
::Message(PW_STATUS_MSG_DOMAIN), such as::pw::Status::Message.PW_STATUS_CFG_MESSAGES_STRING, for other backends: A pointer to the string literal is stored next to the code, so a status is two words.
pw_status cannot see the pw_log backend, so it cannot choose for you.
pw_log/status.h fails to compile if the option does not match the backend.
Bazel: Set
--@pigweed//pw_status:messages=tokenizedor--@pigweed//pw_status:messages=string, for example in the flags of each platform.GN and CMake: Define
PW_STATUS_CFG_MESSAGESinpw_status_CONFIG, e.g.PW_STATUS_CFG_MESSAGES=PW_STATUS_CFG_MESSAGES_TOKENIZED.
Warning
Status codes must be valid enumerators. They are not range checked, and with tokenized messages, a value that needs more bits than the enum’s values do corrupts both the code and the message. Check integers from outside the program before casting them to a status code, e.g. with pw::StatusFromCodeOrUnknown() or pw::IsValidEnum().
Should I use a custom status?#
Custom status types offer significant advantages, but are not a fit for every scenario or project.
Advantages
Resolve ambiguity: Each distinct error can map to its own code. No more wondering which resource was exhausted for
RESOURCE_EXHAUSTED.Better API contracts for callers: APIs only produce codes that make sense. Callers do not have consider codes that will never be returned.
Better API contracts for implementers: API implementers are constrained to defined codes and cannot return codes that do not apply. No need to check that an implementation returned a supported code.
Thoughtful layering of status domains: Prevent users from mindlessly forwarding errors between API layers with PW_TRY, which loses meaning and specificity.
Disadvantages
Cognitive load: Users have to learn different status codes for different APIs.
Enum proliferation: Custom statuses could lead to a proliferation of enums, even when fewer status types would be better.
Whether and how to use custom status types is ultimately a project decision.