Skip to content

Commit a3619e3

Browse files
committed
feat: Add anyhow::Error example
1 parent 9056846 commit a3619e3

File tree

4 files changed

+59
-0
lines changed

4 files changed

+59
-0
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ members = [
1010
"./examples/tauri/src-tauri",
1111
"./examples/legacy",
1212
"./examples/binario",
13+
"./examples/anyhow-error",
1314
]
1415

1516
[workspace.dependencies]

examples/anyhow-error/Cargo.toml

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[package]
2+
name = "anyhow-error"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
rspc = { path = "../../rspc", features = ["typescript"] }
8+
specta.workspace = true
9+
anyhow = "1.0.95"
10+
thiserror = "2.0.11"
11+
12+
[lints]
13+
workspace = true

examples/anyhow-error/bindings.ts

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// This file was generated by [rspc](https://github.com/specta-rs/rspc). Do not edit this file manually.
2+
3+
export type Procedures = {
4+
anyhow: { kind: "query", input: any, output: any, error: any },
5+
}

examples/anyhow-error/src/main.rs

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use rspc::{Procedure, Router};
2+
3+
////////////////////////////////////////////////////////////////////////////////////////////////////
4+
5+
fn main() {
6+
let (_procedures, _types) = Router::new()
7+
.procedure(
8+
//
9+
"anyhow",
10+
Procedure::builder().query(anyhow_procedure),
11+
)
12+
.build()
13+
.expect("router should be built");
14+
}
15+
16+
// Some procedure that needs `anyhow::Error` to be compatible with `rspc`.
17+
async fn anyhow_procedure(_ctx: (), _input: ()) -> Result<String, AnyhowError> {
18+
let response = fallible()?; // `?` converts `anyhow::Error` into `AnyhowError`.
19+
Ok(response)
20+
}
21+
22+
fn fallible() -> Result<String, anyhow::Error> {
23+
anyhow::bail!("oh no!")
24+
}
25+
26+
////////////////////////////////////////////////////////////////////////////////////////////////////
27+
28+
// Make `anyhow::Error` work where `std::error::Error + Send + 'static` is expected.
29+
// NB: Define this only once; afterwards, you can import and use it anywhere.
30+
// See: https://github.com/dtolnay/anyhow/issues/153#issuecomment-833718851
31+
#[derive(Debug, thiserror::Error)]
32+
#[error(transparent)]
33+
struct AnyhowError(#[from] anyhow::Error);
34+
35+
impl rspc::Error for AnyhowError {
36+
fn into_procedure_error(self) -> rspc::ProcedureError {
37+
let message = format!("something bad happened: {}", self);
38+
rspc::ResolverError::new(message, Some(self)).into()
39+
}
40+
}

0 commit comments

Comments
 (0)