exception-handling - 尝试和弹弓/尝试+的区别?

标签 exception-handling clojure

我正在尝试为clj-http返回404时编写一个异常处理程序。根据documentation中的Exceptions部分:

clj-http will throw a Slingshot Stone that can be caught by a regular (catch Exception e ...) or in Slingshot's try+ block



尝试此操作,似乎有些差异我很难弄清楚:
(ns my-app.core
  (:require [clj-http.client :as client])
  (:use [slingshot.slingshot]))

(try
  (client/get "http://some-site.com/broken")
  (catch Exception e (print "I found a problem!")))

=> I found a problem!
   nil

(try+
  (client/get "http://some-site.com/broken")
  (catch Exception e (print "I found a problem!")))

=> ExceptionInfo clj-http: status 404  clj-http.client/wrap-exceptions/fn--1604 (client.clj:147)

最佳答案

如果您不筛选Exception的子类,则可以正常工作:

(try+
  (client/get "http://some-site.com/broken")
  (catch Object _ (print "I found a problem!")))

这里抛出的是带有异常元数据的本地Clojure映射,而不是传统的Java异常。

这样,如果您使用的是Slingshot,则可以在该 map 上进行过滤-使用诸如请求状态,返回的内容,重定向等字段-以使除了块以外的其他块具有比类更多的细粒度选择。例如:
(try+
  (client/get "http://some-site.com/broken")
  (catch [:status 404] {:keys [trace-redirects]}
    (print "No longer exists! (redirected through " trace-redirects ")")))

关于exception-handling - 尝试和弹弓/尝试+的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20708580/

相关文章:

c# - "using"语句是 "bad code"吗?

php - Laravel View 未发现异常

java - 如何为 servlet 的 init() 方法抛出异常

clojure - 如何返回向量?

C++ 在构造函数中捕获异常

python - 处理多个异常时共享 Python 代码

clojure - 是否期望 identity 返回与其参数不同的东西?

clojure - 在Clojure中定义我自己的阅读器宏

eclipse - 如何在 Eclipse 中重新缩进所有代码?

multithreading - 如何在 Clojure 中使用轻量级线程?