-
SummaryI am attempting to implement two examples together: The database table:
Cargo.toml: [dependencies]
anyhow = "1.0"
axum = "0.7"
chrono = "0.4.31"
deadpool-diesel = { version = "0.5", features = ["postgres"] }
diesel = { version = "2.1", features = ["postgres", "chrono"] }
diesel_migrations = "2.1"
dotenvy = "0.15.0"
tokio = { version = "1.35", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" errors.rs: use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
// Make our own error that wraps `anyhow::Error`.
pub struct AppError(anyhow::Error);
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into
// `Result<_, AppError>`. That way you don't need to do that manually.
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
} api.rs: use crate::errors::AppError;
use crate::{models::message::Message, schema::messages};
use axum::{extract::State, response::Json, routing::get, Router};
use diesel::{QueryDsl, RunQueryDsl, SelectableHelper};
pub fn routes(db_pool: deadpool_diesel::postgres::Pool) -> Router {
Router::new()
.route("/messages", get(get_messages))
.with_state(db_pool)
}
async fn get_messages(
State(pool): State<deadpool_diesel::postgres::Pool>,
) -> Result<Json<Vec<Message>>, AppError> {
let conn = pool.get().await?;
let res = conn
.interact(|conn| messages::table.select(Message::as_select()).load(conn))
.await??;
Ok(Json(res))
} But I'm getting two errors. The first one is the first
which goes away if I replace my And the second error: is with
I'm not sure how to handle this error? Would appreciate any suggestions on how to implement generic error handling in axum with diesel. axum version0.7.4 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
I needed to add Is there a way to have anyhow handle boxed errors? |
Beta Was this translation helpful? Give feedback.
just ditch anyhow and go with a generic error handler e.g. https://gist.github.com/manstie/ef93450a0d8521589be7ce59e70e266c