我正在尝试为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/