Skip to content

Commit becff1c

Browse files
committed
Simplify internal wasm error handling
Derive From for conveting internal errors to JsValue with Into::into.
1 parent 9474010 commit becff1c

File tree

5 files changed

+45
-11
lines changed

5 files changed

+45
-11
lines changed

bindings/wasm/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ js-sys = { version = "0.3" }
2020
serde = { version = "1.0", features = ["derive"] }
2121
wasm-bindgen = { version = "0.2", features = ["serde-serialize"] }
2222
wasm-bindgen-futures = { version = "0.4", default-features = false }
23+
flat-enum = { version = "0.1", default-features = false, path = "../../flat-enum" }
2324

2425
[dependencies.identity]
2526
version = "=0.3.0"
@@ -29,6 +30,7 @@ features = ["comm", "wasm"]
2930

3031
[dev-dependencies]
3132
wasm-bindgen-test = { version = "0.3" }
33+
serde_json = { version = "1.0" }
3234

3335
[target.'cfg(target_arch = "wasm32")'.dependencies]
3436
chrono = { version = "0.4", features = ["wasmbind"] }

bindings/wasm/src/credential/credential.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,23 +35,23 @@ impl VerifiableCredential {
3535
if !base.contains_key("@context") {
3636
base.insert(
3737
"@context".into(),
38-
Credential::<()>::base_context().serde_into().map_err(err)?,
38+
Credential::<()>::base_context().serde_into()?,
3939
);
4040
}
4141

4242
let mut types: Vec<String> = match base.remove("type") {
43-
Some(value) => value.serde_into().map(OneOrMany::into_vec).map_err(err)?,
43+
Some(value) => value.serde_into().map(OneOrMany::into_vec)?,
4444
None => Vec::new(),
4545
};
4646

4747
types.insert(0, Credential::<()>::base_type().into());
48-
base.insert("type".into(), types.serde_into().map_err(err)?);
48+
base.insert("type".into(), types.serde_into()?);
4949

5050
if !base.contains_key("issuanceDate") {
5151
base.insert("issuanceDate".into(), Timestamp::now_utc().to_string().into());
5252
}
5353

54-
base.serde_into().map_err(err).map(Self)
54+
base.serde_into().map_err(Into::into).map(Self)
5555
}
5656

5757
#[wasm_bindgen]

bindings/wasm/src/credential/presentation.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ impl VerifiablePresentation {
2525
presentation_id: Option<String>,
2626
) -> Result<VerifiablePresentation, JsValue> {
2727
let credentials: OneOrMany<Credential> = credential_data.into_serde().map_err(err)?;
28-
let holder_url: Url = Url::parse(holder_doc.0.id().as_str()).map_err(err)?;
28+
let holder_url: Url = Url::parse(holder_doc.0.id().as_str())?;
2929

3030
let mut builder: PresentationBuilder = PresentationBuilder::default().holder(holder_url);
3131

@@ -38,10 +38,10 @@ impl VerifiablePresentation {
3838
}
3939

4040
if let Some(presentation_id) = presentation_id {
41-
builder = builder.id(Url::parse(presentation_id).map_err(err)?);
41+
builder = builder.id(Url::parse(presentation_id)?);
4242
}
4343

44-
builder.build().map_err(err).map(Self)
44+
builder.build().map_err(Into::into).map(Self)
4545
}
4646

4747
/// Serializes a `VerifiablePresentation` object as a JSON object.

bindings/wasm/src/crypto/key_pair.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,14 @@ impl KeyPair {
3131
/// Generates a new `KeyPair` object.
3232
#[wasm_bindgen(constructor)]
3333
pub fn new(type_: KeyType) -> Result<KeyPair, JsValue> {
34-
KeyPair_::new(type_.into()).map_err(err).map(Self)
34+
KeyPair_::new(type_.into()).map_err(Into::into).map(Self)
3535
}
3636

3737
/// Parses a `KeyPair` object from base58-encoded public/secret keys.
3838
#[wasm_bindgen(js_name = fromBase58)]
3939
pub fn from_base58(type_: KeyType, public_key: &str, secret_key: &str) -> Result<KeyPair, JsValue> {
40-
let public: PublicKey = decode_b58(public_key).map_err(err)?.into();
41-
let secret: SecretKey = decode_b58(secret_key).map_err(err)?.into();
40+
let public: PublicKey = decode_b58(public_key)?.into();
41+
let secret: SecretKey = decode_b58(secret_key)?.into();
4242

4343
Ok(Self((type_.into(), public, secret).into()))
4444
}

bindings/wasm/src/utils.rs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,42 @@
33

44
use wasm_bindgen::JsValue;
55

6-
/// Convert errors so they are readable in JS
6+
/// Convert errors to strings so they are readable in JS
77
pub fn err<T>(error: T) -> JsValue
88
where
99
T: ToString,
1010
{
1111
error.to_string().into()
1212
}
13+
14+
// Alternative to implementing From for JsValue when deriving FlatEnum
15+
// /// Convert errors that derive FlatEnum into JS
16+
// pub fn flat_err<T, V>(error: T) -> JsValue
17+
// where
18+
// T: flat_enum::IntoFlatEnum<V>,
19+
// V: flat_enum::FlatEnum,
20+
// {
21+
// // TODO: check that unwrap is infallible here?
22+
// JsValue::from_serde(&error.into_flat_enum()).unwrap()
23+
// }
24+
25+
#[cfg(test)]
26+
mod tests {
27+
use flat_enum::IntoFlatEnum;
28+
29+
#[test]
30+
fn test_js_error() {
31+
let err = identity::credential::Error::DIDError(
32+
identity::did::Error::CoreError(
33+
identity::core::Error::DecodeBitmap(
34+
std::io::Error::new(std::io::ErrorKind::Other, "something went wrong!")
35+
)
36+
)
37+
);
38+
println!("{}", err.to_string()); // Failed to decode roaring bitmap: something went wrong!
39+
let json_str = serde_json::to_string(&err.to_string()).unwrap();
40+
println!("{}", json_str); // "Failed to decode roaring bitmap: something went wrong!"
41+
let json = serde_json::to_string(&err.into_flat_enum()).unwrap();
42+
println!("{}", json); // {"code":"DIDError","description":"Failed to decode roaring bitmap: something went wrong!"}
43+
}
44+
}

0 commit comments

Comments
 (0)