Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<JSON<User>, 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
Expand Down