diff --git a/README.md b/README.md index fb8fefe6b..77c14ba35 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,59 @@ async fn create_user( } ``` +### Typed errors + +```rust,no_run +use ohkami::{Response, IntoResponse}; +use ohkami::serde::Serialize; +use ohkami::format::JSON; +use ohkami::fang::Context; + +enum MyError { + Sqlx(sqlx::Error), +} +impl IntoResponse for MyError { + fn into_response(self) -> Response { + match self { + Self::Sqlx(e) => Response::InternalServerError(), + } + } +} + +#[derive(Serialize)] +struct User { + id: u32, + name: String, +} + +async fn get_user( + id: u32, + Context(pool): Context<'_, sqlx::PgPool>, +) -> Result, MyError> { + let sql = r#" + SELECT name FROM users WHERE id = $1 + "#; + let name = sqlx::query_scalar::<_, String>(sql) + .bind(id as i64) + .fetch_one(pool) + .await + .map_err(MyError::Sqlx)?; + + Ok(JSON(User { id, name })) +} +``` + +[thiserror](https://crates.io/crates/thiserror) will improve error conversion: + +```rust,ignore + let name = sqlx::query_salor_as::<_, String>(sql) + .bind(id) + .fetch_one(pool) + // .await + // .map_err(MyError::Sqlx)?; + .await?; +``` + ### Static directory serving ```rust,no_run