-
Hello! Now I would very much like to be able to do the following: use library_crate::ret_error; //a function returning Result<(), AdapterError>
#[get("/some/route")]
async fn endpoint() -> Result<(), AdapterError> {
ret_error().await?;
Ok(())
} The issue is that Currently I pass |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
You can create another Error struct or enum or just type and impl From<AdapterError> for Error. This way you could use almost the same code as in your example, but you have to change from Small example: use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("jwt error: {0}")]
JwtError(#[from] jsonwebtoken::errors::Error),
#[error("diesel query error: {0}")]
DieselQueryError(#[from] diesel::result::Error),
#[error("wrong credentials")]
WrongCredentials,
}
impl From<Error> for api::Error {
fn from(err: Error) -> Self {
let (status, reason) = match err {
_ => (Status::InternalServerError, "Unknown"),
};
let error = api::ErrorDetails {
reason: reason.to_string(),
description: err.to_string(),
};
(status, error).into()
}
} |
Beta Was this translation helpful? Give feedback.
-
For eventual users finding themselves in the same predicament, here's what I came up with. use thiserror;
use rocket::*; //only for the sake of this simplified example
//the foreign crate's `Error` type and a function that returns `Result<(), AdapterError>`
use foreign::{AdapterError, returning_adapter_error};
#[derive(Debug, thiserror::Error)]
#[error("We couldn't process your request: {reason}. Error: {source}")]
struct ApiError<'a> {
status: Status,
reason: &'a str,
#[source]
source: AdapterError,
}
impl<'a> From<AdapterError> for ApiError<'a> {
fn from(err: AdapterError) -> Self {
let (status, reason) = match &err {
//you handle the variants and how they're processed here
AdapterError::SqlxError(_) => (
Status::InternalServerError,
"sqlx driver failed to query the database",
),
_ => todo!(),
};
ApiError {
status,
reason,
source: err,
}
}
}
impl<'r, 'o: 'r> Responder<'r, 'o> for ApiError<'o> {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
Response::build()
.header(ContentType::JSON)
.status(self.status)
.sized_body(self.reason.len(), Cursor::new(self.reason))
.ok()
}
}
#[get("/some/route")]
async fn endpoint<'a>() -> Result<(), ApiError> {
//remember this function returns `Result<(), AdapterError>`
Ok(returning_adapter_error()?);
} |
Beta Was this translation helpful? Give feedback.
You can create another Error struct or enum or just type and impl From<AdapterError> for Error. This way you could use almost the same code as in your example, but you have to change from
Result<(), AdapterError>
toResult<(), Error
Small example: