I'm trying to write an exception handler for when clj-http
returns 404. According to the Exceptions section in the documentation:
clj-http will throw a Slingshot Stone that can be caught by a regular (catch Exception e ...) or in Slingshot's try+ block
Trying this, it looks like there are some differences that I have trouble figuring out:
(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)
If you don't filter for subclasses of Exception
, that works fine:
(try+
(client/get "http://some-site.com/broken")
(catch Object _ (print "I found a problem!")))
The thing being thrown here is a native Clojure map with exception metadata, not traditional Java exception as such.
As such, if you're using Slingshot, you can filter on that map -- with fields such as request status, content returned, redirects, etc -- to have except blocks with much more fine-grained selection than just the class. For instance:
(try+
(client/get "http://some-site.com/broken")
(catch [:status 404] {:keys [trace-redirects]}
(print "No longer exists! (redirected through " trace-redirects ")")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With