dea*_*ost 8 exception-handling clojure
我正在尝试为when clj-http返回404 时编写异常处理程序.根据文档中的Exceptions部分:
clj-http将抛出一个Slingshot Stone,它可以被常规捕获(捕获Exception e ...)或者在Slingshot的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)
Run Code Online (Sandbox Code Playgroud)
Cha*_*ffy 12
如果你没有过滤子类Exception,那就可以了:
(try+
(client/get "http://some-site.com/broken")
(catch Object _ (print "I found a problem!")))
Run Code Online (Sandbox Code Playgroud)
这里抛出的东西是带有异常元数据的本地Clojure映射,而不是传统的Java异常.
因此,如果您正在使用Slingshot,您可以在该地图上进行过滤 - 包括请求状态,返回内容,重定向等字段 - 除了具有比类更细粒度选择的块之外.例如:
(try+
(client/get "http://some-site.com/broken")
(catch [:status 404] {:keys [trace-redirects]}
(print "No longer exists! (redirected through " trace-redirects ")")))
Run Code Online (Sandbox Code Playgroud)