Skip to main content

GrpcError

Derive Macro GrpcError 

Source
#[derive(GrpcError)]
{
    // Attributes available to this derive:
    #[grpc]
    #[grpc_error]
    #[tracing]
}
Expand description

Derive macro for gRPC error enums.

Generates:

  • From<Self> for tonic::Status

Enum-level defaults can be declared with #[grpc_error(...)] and overridden per variant with #[grpc(...)].

Supported attributes:

  • code = "invalid_argument"
  • message = "custom text"
  • message = field_name
  • transparent (variant-only)
  • tracing = <level> inside #[grpc_error(...)] or #[grpc(...)]
  • #[tracing(level)]: backward-compatible shorthand at variant level

gRPC code values accepted by #[grpc(code = "...")]:

  • ok
  • cancelled
  • unknown
  • invalid_argument
  • deadline_exceeded
  • not_found
  • already_exists
  • permission_denied
  • resource_exhausted
  • failed_precondition
  • aborted
  • out_of_range
  • unimplemented
  • internal
  • unavailable
  • data_loss
  • unauthenticated

§Example

use sword::prelude::*;
use thiserror::Error;

#[derive(Debug, Error, GrpcError)]
#[grpc_error(code = "internal", tracing = error)]
enum UserError {
    #[grpc(code = "not_found", tracing = info)]
    #[error("User not found: {id}")]
    NotFound { id: String },

    #[grpc(code = "invalid_argument", message = client_message)]
    #[error("Validation error: {internal}")]
    Validation {
        client_message: String,
        internal: String,
    },

    #[grpc(transparent)]
    #[error("Database error: {0}")]
    Database(#[from] anyhow::Error),
}