tonic icon indicating copy to clipboard operation
tonic copied to clipboard

`StatusCode` trait

Open maxwase opened this issue 6 months ago • 0 comments

Feature Request

Crates

tonic

Motivation

The trait can be useful when dealing with error statuses. tonic exposes the Status::from_error associated function, which creates a new status with a hardcoded Code::Unknown as its status code. With an additional boundary, it would be easy to define the error code.

P.S. It would also be great to include error backtrace when it's present by iterating though its sources

Proposal

Move out the method into a trait

pub trait ErrorCode {
    fn code(&self) -> tonic::Code;
}

So that we could

use tonic::Code;

impl ErrorCode for Error {
    fn code(&self) -> Code {
        match self {
            Error::Two(_) => Code::FailedPrecondition,
            _ => Code::Internal,
        }
    }
}

Alternatives

It would be great to implement this via std::process::Termination trait instead, but getting the code as i32 from std::process::ExitCode is not stable yet.

maxwase avatar Jun 27 '25 14:06 maxwase