How to catch any Javascript exception in Clojurescript?

前端 未结 3 1314
甜味超标
甜味超标 2021-02-11 21:56

In my communication layer I have a need to be able to catch ANY javascript exception, log it down and proceed as I normally would do. Current syntax for catching exceptions in C

3条回答
  •  鱼传尺愫
    2021-02-11 22:05

    It looks like js/Object catches them all (tested on https://himera.herokuapp.com):

    cljs.user> (try (throw (js/Error. "some error")) (catch js/Object e (str "Caught: " e)))
    "Caught: Error: some error"
    cljs.user> (try (throw "string error") (catch js/Object e (str "Caught: " e)))
    "Caught: string error"
    cljs.user> (try (js/eval "throw 'js error';") (catch js/Object e (str "Caught: " e)))
    "Caught: js error"
    

    One thing to watch out for is lazy sequences. If an error is thrown in a lazy sequence that part of the code might not be executed until after you've exited the try function. For example:

    cljs.user> (try (map #(if (zero? %) (throw "some error")) [1]))
    (nil)
    cljs.user> (try (map #(if (zero? %) (throw "some error")) [0]))
    ; script fails with "Uncaught some error"
    

    In that last case, map creates a lazy sequence and the try function returns it. Then, when the repl tries to print the sequence to the console, it's evaluated and the error gets thrown outside of the try expression.

提交回复
热议问题