在我的通信层中,我需要能够捕获任何javascript异常,将其记录下来并像往常一样继续操作。 在Clojurescript中捕获异常的当前语法规定我需要指定被捕获的异常的类型。
我尝试在catch表单中使用nil,js / Error,js / object,但它没有捕获任何javascript异常(可以将字符串作为对象的类型)。
我很感激任何提示如何在Clojurescript中本地完成。
答案 0 :(得分:39)
我在David Nolen "Light Table ClojureScript Tutorial"
中找到了另一个可能的答案;; Error Handling
;; ============================================================================
;; Error handling in ClojureScript is relatively straightforward and more or
;; less similar to what is offered in JavaScript.
;; You can construct an error like this.
(js/Error. "Oops")
;; You can throw an error like this.
(throw (js/Error. "Oops"))
;; You can catch an error like this.
(try
(throw (js/Error. "Oops"))
(catch js/Error e
e))
;; JavaScript unfortunately allows you to throw anything. You can handle
;; this in ClojureScript with the following.
(try
(throw (js/Error. "Oops"))
(catch :default e
e))
答案 1 :(得分:5)
看起来js / Object会捕获它们(在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"
需要注意的一件事是懒惰的序列。如果在延迟序列中抛出错误,则在退出try函数之前可能不会执行部分代码。例如:
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"
在最后一种情况下,map会创建一个惰性序列,try函数会返回它。然后,当repl尝试将序列打印到控制台时,会对其进行评估,并在try表达式之外抛出错误。
答案 2 :(得分:3)
我想我刚刚在这个链接中找到了解决方案 https://groups.google.com/forum/#!topic/clojure/QHaTwjD4zzU
我在这里复制内容: 该解决方案由Herwig Hochleitner出版
尝试使用clojurescript实际上是一个使用内置try *的宏 并添加类型调度。所以要抓住一切,只需使用(尝试* ... (赶上...))。这直接映射到javascript的尝试。
现在我的实施工作正在进行中:
(defn is-dir? [the_dir]
(try*
(if-let [stat (.statSync fs the_dir )]
(.isDirectory stat)
false)
(catch e
(println "catching all exceptions, include js/exeptions")
false
)
)
)
我希望它可以帮助你 涓