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.
This commit is contained in:
Cecylia Bocovich 2022-11-15 21:57:49 -05:00
parent 6e3525ac4c
commit ebae7fb600
2 changed files with 24 additions and 7 deletions

View File

@ -13,3 +13,7 @@ crate-type = ["cdylib"]
lox = { git = "https://git-crysp.uwaterloo.ca/iang/lox.git" } lox = { git = "https://git-crysp.uwaterloo.ca/iang/lox.git" }
wasm-bindgen = "0.2" wasm-bindgen = "0.2"
serde_json = "1.0.87" serde_json = "1.0.87"
console_error_panic_hook = "0.1.7"
rand = { version = "0.7", features = ["wasm-bindgen"] }

View File

@ -2,6 +2,8 @@ use wasm_bindgen::prelude::*;
use lox::OPENINV_LENGTH; use lox::OPENINV_LENGTH;
use lox::proto::open_invite; use lox::proto::open_invite;
use serde_json; use serde_json;
use std::array::TryFromSliceError;
use std::panic;
#[wasm_bindgen] #[wasm_bindgen]
extern { extern {
@ -9,15 +11,26 @@ extern {
pub fn log(s: &str); pub fn log(s: &str);
} }
#[wasm_bindgen]
pub fn set_panic_hook() {
panic::set_hook(Box::new(console_error_panic_hook::hook));
}
#[wasm_bindgen] #[wasm_bindgen]
pub fn open_invite(invite: &[u8]) { pub fn open_invite(invite: &[u8]) {
log(&format!("Using invite: {:?}", invite));
let (request, _state) = open_invite::request(&validate_invite(invite)); match validate(invite) {
Ok(token) => {
let (request, _state) = open_invite::request(&token);
let serialized_request = serde_json::to_string(&request).unwrap(); let serialized_request = serde_json::to_string(&request).unwrap();
log(&format!("request: {}", serialized_request)); log(&format!("Formatted open invite request: {}", serialized_request));
},
Err(e) => {
log(&format!("{:?}", e));
},
}
} }
fn validate(invite: &[u8]) -> Result<[u8; OPENINV_LENGTH], TryFromSliceError> {
fn validate_invite(invite: &[u8]) -> [u8; OPENINV_LENGTH] { invite.try_into()
invite.try_into().expect("slice with incorrect length")
} }