diff options
| author | Andrey Orst <andreyorst@gmail.com> | 2020-12-31 09:44:57 +0300 |
|---|---|---|
| committer | Andrey Orst <andreyorst@gmail.com> | 2020-12-31 09:44:57 +0300 |
| commit | a2b08f721c28b3b56a802031bc35df6a68b219d8 (patch) | |
| tree | fb41c48902d552e6e2f4cf104770156239b96375 | |
| parent | b414ab62c4e3e299bb3ca1dc04944d428574c1f0 (diff) | |
fix(macros): fix bug in try, add tests
| -rw-r--r-- | cljlib-macros.fnl | 9 | ||||
| -rw-r--r-- | tests/macros.fnl | 32 |
2 files changed, 35 insertions, 6 deletions
diff --git a/cljlib-macros.fnl b/cljlib-macros.fnl index 26c80d7..19b0107 100644 --- a/cljlib-macros.fnl +++ b/cljlib-macros.fnl @@ -1055,23 +1055,20 @@ clauses when we push body epression." (add-to-try finally catches try form)) (add-to-try finally catches try form))) `(match (pcall ,try) - (true res#) (do ,(. finally 1) res#) + (true _#) (do ,(. finally 1) _#) ,(make-catch-clauses catches finally)))) (attach-meta try {:fnl/arglist [:body* :catch-clause* :finally-clause?] :fnl/docstring "General purpose try/catch/finally macro. - -(try expression* catch-clause* finally-clause?) - Wraps its body in `pcall` and checks the return value with `match` macro. -Catch-clause is written either as (catch symbol body*), thus acting as +Catch clause is written either as (catch symbol body*), thus acting as catch-all, or (catch value body*) for catching specific errors. It is possible to have several `catch` clauses. If no `catch` clauses specified, an implicit catch-all clause is created. -Finally-clause is optional, and written as (finally body*). If +Finally clause is optional, and written as (finally body*). If present, it must be the last clause in the `try` form, and the only `finally` clause. Note that `finally` clause is for side effects only, and runs either after succesful run of `try` body, or after any diff --git a/tests/macros.fnl b/tests/macros.fnl index 9ac9d95..e387eb2 100644 --- a/tests/macros.fnl +++ b/tests/macros.fnl @@ -203,3 +203,35 @@ (let [a [:a 1 :b 2]] (assert-eq (empty a) []) (assert-eq (getmetatable (empty a)) {:cljlib/type :seq})))) + +(deftest try + (testing "try" + (assert-eq (try (+ 1 2 3)) 6) + (assert-eq (try (+ 1 2 3) (catch _ 0) (finally 10)) 6) + (assert-eq (try (+ 1 2 3 nil) (catch _ 0) (finally 10)) 0) + (assert-eq (try (+ 1 2 3 nil) (catch _) (finally 10)) nil)) + (testing "catch-all" + (assert-eq (try + (error 10) + (catch _ :pass)) + :pass) + (assert-eq (try + (error 10) + (catch err err)) + 10)) + (testing "finally" + (let [tbl []] + (try + (try + (finally (table.insert tbl 1))) + (try + (error 10) + (catch _ (table.insert tbl 2)) + (finally (table.insert tbl 3))) + (try + (error 20) + (finally (table.insert tbl 4))) + (catch _ (table.insert tbl 5)) + (catch 20 (table.insert tbl 6)) + (finally (table.insert tbl 7))) + (assert-eq tbl [1 2 3 4 5 7])))) |