Skip to content

Commit

Permalink
[#16] throw when streaming based on status code
Browse files Browse the repository at this point in the history
  • Loading branch information
borkdude committed Apr 26, 2020
1 parent 2a4fe05 commit b4da21c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
23 changes: 12 additions & 11 deletions src/babashka/curl.clj
Original file line number Diff line number Diff line change
Expand Up @@ -192,21 +192,23 @@
#{200 201 202 203 204 205 206 207 300 301 302 303 304 307})

(defn- should-throw? [response opts]
(let [exceptional-status? (not (unexceptional-status? (:status response)))
nonzero-exit? (not (zero? (:exit response)))]
(and (:throw opts)
(or exceptional-status? nonzero-exit?))))
(and (:throw opts)
;; when streaming, we don't know the exit code yet, so it's too early
;; to say if we should throw
(or (not (unexceptional-status? (:status response)))
(and (not (identical? :stream (:as opts)))
(not (zero? (:exit response)))))))

(defn- build-ex-msg [response]
(cond
(:status response)
(str "status " (:status response))
(str "babashka.curl: status " (:status response))

(not (str/blank? (:err response)))
(:err response)

:else
"error"))
"babashka.curl: error"))

(defn request [opts]
(let [header-file (File/createTempFile "babashka.curl" ".headers")
Expand All @@ -220,11 +222,10 @@
response)
response (if (:debug opts)
(assoc response
:command args
:options opts)
response)
stream? (identical? :stream (:as opts))]
(if (and (not stream?) (should-throw? response opts))
:command args
:options opts)
response)]
(if (should-throw? response opts)
(throw (ex-info (build-ex-msg response) response))
response)))

Expand Down
17 changes: 9 additions & 8 deletions test/babashka/curl_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -207,15 +207,16 @@
response (ex-data ex)]
(is (= 404 (:status response)))
(is (zero? (:exit response)))))
(testing "should not throw"
(let [response (curl/get "https://httpstat.us/404" {:throw false})]
(is (= 404 (:status response)))
(is (zero? (:exit response)))))
(testing "should not throw when streaming"
(let [response (curl/get "https://httpstat.us/404" {:throw true
:as :stream})]
(testing "should throw when streaming based on status code"
(let [ex (is (thrown? ExceptionInfo (curl/get "https://httpstat.us/404" {:throw true
:as :stream})))
response (ex-data ex)]
(is (= 404 (:status response)))
(is (= "404 Not Found" (slurp (:body response))))
(is (= "" (slurp (:err response))))
(is (delay? (:exit response)))
(is (zero? @(:exit response))))))
(is (zero? @(:exit response)))))
(testing "should not throw"
(let [response (curl/get "https://httpstat.us/404" {:throw false})]
(is (= 404 (:status response)))
(is (zero? (:exit response))))))

0 comments on commit b4da21c

Please sign in to comment.