Skip to main content

ErrorCode

Derive Macro ErrorCode 

Source
#[derive(ErrorCode)]
{
    // Attributes available to this derive:
    #[error_code]
}
Expand description

Derive macro for the ErrorCode trait.

Automatically generates an error_code() implementation that returns "TypeName::VariantName" for each enum variant, or "TypeName" for structs.

§Example

use xmtp_common::ErrorCode;

#[derive(Debug, thiserror::Error, ErrorCode)]
pub enum GroupError {
    #[error("Group not found")]
    NotFound,  // Returns "GroupError::NotFound"

    #[error("Storage error: {0}")]
    #[error_code(inherit)]  // Delegates to StorageError::error_code()
    Storage(#[from] StorageError),
}

§Attributes

  • #[error_code(inherit)] - Delegate to the inner error’s error_code() method. Use this for single-field variants that wrap another error implementing ErrorCode.

  • #[error_code(remote = "path::Type")] - Implement ErrorCode for a remote type. The derived item should mirror the remote type’s shape. Default codes use the derived item’s type name, so keep it aligned with the remote type’s name unless overridden.

  • #[error_code("CustomCode")] - Override the generated code with a custom value. Use this to maintain backwards compatibility when renaming variants.

§Example: Custom Code for Backwards Compatibility

#[derive(Debug, thiserror::Error, ErrorCode)]
pub enum MyError {
    // Renamed from "OldName" but keeps the old error code
    #[error("new name")]
    #[error_code("MyError::OldName")]
    NewName,
}