Crates.io | tonic-error |
lib.rs | tonic-error |
version | 0.3.0 |
source | src |
created_at | 2022-07-01 22:33:13.421331 |
updated_at | 2022-07-05 05:07:15.938737 |
description | Derive trait to allow passing of custom errors through tonic Status responses. |
homepage | https://github.com/rthomas/tonic-error |
repository | https://github.com/rthomas/tonic-error |
max_upload_size | |
id | 617536 |
size | 17,492 |
A helper trait to assist with passing error types through return tonic::Status
messages.
This works with the thiserror
crates, but using that is not required. If you
are not using thiserror
then at the moment you will need to manually implement
std::fmt::Display
for your type. Your error type will also need to derive
serde::{Serialize, Deserialize}
.
In order to use this, you will need to #[derive(TonicError)]
on your error type.
#[derive(Debug, Error, TonicError, Serialize, Deserialize)]
pub enum MathsError {
#[error("division by zero for inputs: a={0} b={1}")]
DivByZero(i32, i32),
}
The TonicError
trait provides implementations of std::convert::TryFrom
for
your type, and an implementation of std::convert::From
for tonic::Status
.
These examples are taken from the included examples.
async fn div(&self, req: Request<DivRequest>) -> Result<Response<DivResponse>, Status> {
let req = req.into_inner();
if req.b == 0 {
return Err(MathsError::DivByZero(req.a, req.b).into());
}
let result = req.a as f64 / req.b as f64;
Ok(Response::new(DivResponse { result }))
}
pub async fn div(&mut self, a: i32, b: i32) -> Result<f64, MathsError> {
let req = Request::new(DivRequest { a, b });
let resp = match self.client.div(req).await {
Ok(r) => r,
Err(e) => match e.code() {
Code::Internal => {
return Err(e.try_into().expect("could not convert status to error"))
}
_ => panic!("error making rpc call: {e}"),
},
};
Ok(resp.into_inner().result)
}
See the tonic-error-example
subdirectory in this repo for a working
client/server example.
This is released under the Apache 2.0 license.