From ebae7fb6004ade4702a6727d0308e3b252c5777d Mon Sep 17 00:00:00 2001 From: Cecylia Bocovich Date: Tue, 15 Nov 2022 21:57:49 -0500 Subject: [PATCH] Improve error handling and add rand dependency This makes panics more visible in the console and fixes a weird bug where the rand package was throwing an error. --- crates/lox-wasm/Cargo.toml | 4 ++++ crates/lox-wasm/src/lib.rs | 27 ++++++++++++++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/crates/lox-wasm/Cargo.toml b/crates/lox-wasm/Cargo.toml index 055a82e..58336b8 100644 --- a/crates/lox-wasm/Cargo.toml +++ b/crates/lox-wasm/Cargo.toml @@ -13,3 +13,7 @@ crate-type = ["cdylib"] lox = { git = "https://git-crysp.uwaterloo.ca/iang/lox.git" } wasm-bindgen = "0.2" serde_json = "1.0.87" + +console_error_panic_hook = "0.1.7" + +rand = { version = "0.7", features = ["wasm-bindgen"] } diff --git a/crates/lox-wasm/src/lib.rs b/crates/lox-wasm/src/lib.rs index 5f30efe..6a50392 100644 --- a/crates/lox-wasm/src/lib.rs +++ b/crates/lox-wasm/src/lib.rs @@ -2,6 +2,8 @@ use wasm_bindgen::prelude::*; use lox::OPENINV_LENGTH; use lox::proto::open_invite; use serde_json; +use std::array::TryFromSliceError; +use std::panic; #[wasm_bindgen] extern { @@ -9,15 +11,26 @@ extern { pub fn log(s: &str); } +#[wasm_bindgen] +pub fn set_panic_hook() { + panic::set_hook(Box::new(console_error_panic_hook::hook)); +} + #[wasm_bindgen] pub fn open_invite(invite: &[u8]) { - - let (request, _state) = open_invite::request(&validate_invite(invite)); - let serialized_request = serde_json::to_string(&request).unwrap(); - log(&format!("request: {}", serialized_request)); + log(&format!("Using invite: {:?}", invite)); + match validate(invite) { + Ok(token) => { + let (request, _state) = open_invite::request(&token); + let serialized_request = serde_json::to_string(&request).unwrap(); + log(&format!("Formatted open invite request: {}", serialized_request)); + }, + Err(e) => { + log(&format!("{:?}", e)); + }, + } } - -fn validate_invite(invite: &[u8]) -> [u8; OPENINV_LENGTH] { - invite.try_into().expect("slice with incorrect length") +fn validate(invite: &[u8]) -> Result<[u8; OPENINV_LENGTH], TryFromSliceError> { + invite.try_into() }