Skip to content

Commit 06afc25

Browse files
Merge pull request #342 from TmLev/main
Add `anyhow::Error` example
2 parents fd60b3d + c5b37e6 commit 06afc25

File tree

4 files changed

+65
-0
lines changed

4 files changed

+65
-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",
1314
]
1415

1516
[workspace.dependencies]

examples/anyhow/Cargo.toml

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

examples/anyhow/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/src/main.rs

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

0 commit comments

Comments
 (0)