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" }
wasm-bindgen = "0.2"
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::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()
}