Skip to main content

hashiverse_client_wasm/
with_js_context.rs

1use wasm_bindgen::JsValue;
2use anyhow::anyhow;
3
4
5pub trait JsResultExt<T> {
6    fn with_js_context<F, S>(self, f: F) -> anyhow::Result<T>
7    where
8        F: FnOnce() -> S,
9        S: Into<String>;
10}
11
12impl<T> JsResultExt<T> for std::result::Result<T, JsValue> {
13    fn with_js_context<F, S>(self, f: F) -> anyhow::Result<T>
14    where
15        F: FnOnce() -> S,
16        S: Into<String>
17    {
18        self.map_err(|e| anyhow!("{}: {:?}", f().into(), e))
19    }
20}
21
22impl<T> JsResultExt<T> for std::result::Result<T, indexed_db_futures::error::Error> {
23    fn with_js_context<F, S>(self, f: F) -> anyhow::Result<T>
24    where
25        F: FnOnce() -> S,
26        S: Into<String>
27    {
28        // IdbError usually implements Display, so we can use {} instead of {:?}
29        self.map_err(|e| anyhow::anyhow!("{}: {}", f().into(), e))
30    }
31}