tonic-types
A collection of useful protobuf types that can be used with tonic.
This crate also introduces the StatusExt trait and implements it in
tonic::Status, allowing the implementation of the gRPC Richer Error Model
with tonic in a convenient way.
Usage
Useful protobuf types are available through the pb module. They can be
imported and worked with directly.
The StatusExt trait adds associated functions to tonic::Status that can
be used on the server side to create a status with error details, which can then
be returned to gRPC clients. Moreover, the trait also adds methods to
tonic::Status that can be used by a tonic client to extract error details,
and handle them with ease.
Examples
The examples below cover a basic use case of the gRPC Richer Error Model. More complete server and client implementations are provided in the Richer Error example, located in the main repo examples directory.
Server Side: Generating tonic::Status with an ErrorDetails struct
use ;
use ;
// ...
// Inside a gRPC server endpoint that returns `Result<Response<T>, Status>`
// Create empty `ErrorDetails` struct
let mut err_details = new;
// Add error details conditionally
if some_condition
if other_condition
// Check if any error details were set and return error status if so
if err_details.has_bad_request_violations
// Handle valid request
// ...
Client Side: Extracting an ErrorDetails struct from tonic::Status
use ;
use StatusExt;
// ...
// Where `req_result` was returned by a gRPC client endpoint method
Working with different error message types
Multiple examples are provided at the ErrorDetails doc. Instructions about
how to use the fields of the standard error message types correctly are provided
at error_details.proto.
Alternative tonic::Status associated functions and methods
In the StatusExt doc, an alternative way of interacting with
tonic::Status is presented, using vectors of error details structs wrapped
with the ErrorDetail enum. This approach can provide more control over the
vector of standard error messages that will be generated or that was received,
if necessary. To see how to adopt this approach, please check the
StatusExt::with_error_details_vec and StatusExt::get_error_details_vec
docs, and also the main repo's Richer Error example directory.
Besides that, multiple examples with alternative error details extraction
methods are provided in the StatusExt doc, which can be specially
useful if only one type of standard error message is being handled by the
client. For example, using StatusExt::get_details_bad_request is a
more direct way of extracting a BadRequest error message from
tonic::Status.