hljs: binding: catch hljs errors when specifying language

the language may not exist. do not crash the entire program due to this
This commit is contained in:
Peter Cai 2020-04-12 17:01:45 +08:00
parent f519152465
commit 311b9a0d26
No known key found for this signature in database
GPG Key ID: 71F5FB4E4F3FD54F
3 changed files with 10 additions and 5 deletions

View File

@ -120,7 +120,7 @@ impl Post {
// library updates. Updaing this value invalidates all
// existing cache and they will be recompiled when someone
// visits.
const CACHE_VERSION: &'static str = "0015";
const CACHE_VERSION: &'static str = "0017";
// The prefix path used for caching remote images
pub const IMG_CACHE_PREFIX: &'static str = "/imgcache/";

View File

@ -12,6 +12,11 @@ pub fn highlight_auto(code: &str) -> String {
}
pub fn highlight(lang: &str, code: &str) -> String {
Reflect::get(&hljs_highlight(lang, code), &"value".into())
.unwrap().as_string().unwrap()
match hljs_highlight(lang, code) {
Ok(res) => Reflect::get(&res, &"value".into())
.unwrap().as_string().unwrap(),
// This can throw error if `lang` is not supported
// or not imported by build.rs (and thus config.json)
Err(_) => code.to_owned()
}
}

View File

@ -2,6 +2,6 @@
extern "C" {
#[wasm_bindgen(js_name = "highlightAuto")]
fn hljs_highlight_auto(code: &str) -> JsValue;
#[wasm_bindgen(js_name = "highlight")]
fn hljs_highlight(lang: &str, code: &str) -> JsValue;
#[wasm_bindgen(catch, js_name = "highlight")]
fn hljs_highlight(lang: &str, code: &str) -> Result<JsValue, JsValue>;
}