Skip to main content

api_error_kind

Macro api_error_kind 

Source
macro_rules! api_error_kind {
    {
        $(#[$enum_meta:meta])*
        pub enum $error_kind_name:ident {
            $( #[doc = $unknown_msg:literal] )*
            Unknown(ErrorCode),

            $(
                // use the doc string for the error message
                $( #[doc = $item_msg:literal] )*
                $item_name:ident = $item_code:literal
            ),*

            $(,)?
        }
    } => { ... };
}
Expand description

Make all of lexe_api_core available under [lexe_api].

NOTE: Any crates which can depend on lexe_api_core directly (without lexe-api) should do so to avoid [lexe_api] dependencies. This macro takes an error kind enum declaration and generates impls for the trait ApiErrorKind (and its dependent traits).

Each invocation should be paired with a ToHttpStatus impl.

§Example

api_error_kind! {
    #[derive(Copy, Clone, Debug, Eq, PartialEq)]
    pub enum FooErrorKind {
        /// Unknown error
        Unknown(ErrorCode),

        /// A Foo error occured
        Foo = 1,
        /// Bar failed to complete
        Bar = 2,
    }
}

impl ToHttpStatus for FooErrorKind {
    fn to_http_status(&self) -> StatusCode {
        use FooErrorKind::*;
        match self {
            Unknown(_) => SERVER_500_INTERNAL_SERVER_ERROR,

            Foo => CLIENT_400_BAD_REQUEST,
            Bar => SERVER_500_INTERNAL_SERVER_ERROR,
        }
    }
}
  • All error kind types must have an Unknown(ErrorCode) variant and it must be first. This handles any unrecognized errors seen from remote services and preserves the error code for debugging / propagating.

  • Doc strings on the error variants are used for ApiErrorKind::to_msg and the fmt::Display impl.