Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try and slingshot/try+ differences?

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)
like image 307
deadghost Avatar asked Dec 20 '13 17:12

deadghost


1 Answers

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 ")")))
like image 83
Charles Duffy Avatar answered Sep 28 '22 02:09

Charles Duffy