Clojure/ClojureScript try...catch

clojure
clojurescript

#1

I am just coming to ClojureScript trying to have CLI-matic work on it. My biggest pain point, at the moment, is try/catch blocks and throw calls. I would like to have as much logic as possible in a common .cljc file, and defer to functions help in .clj/.cljs the calling of platform-specific features.

I mean, as exceptions are platform-specific, how do you handle this case for code that is supposed to be platform-agnostic? write your own try/catch and throws macros, that resolve differently for each platform? or is there something ready? try/catch block are control, so I’d hate to port a full function just because there is a try/catch block in it, or it needs to blow up on errors…


#2

I am not 100% sure what you mean, but I wrote a couple of .cljc macros here that run a body in a scope with a try/catch construction:


#3

I’d suggest using portable ex-info and related functions (ex-data, ex-message, ex-cause) for creating and pulling apart exceptions when possible.

For catching exceptions I think something like https://dev.clojure.org/jira/browse/CLJ-1293 would ultimately help in writing portable code, but in the meanwhile reader conditionals seem to be the way to go.


#4

I personally hate the reader conditionals in shared code, but I think there is no other way.


#5

Thanks for the suggestion. I did not know about ex-... functions (like - I fear - I don’t know much about 90% of core…)


#6

It’s probably worth mentioning that ex-message and ex-cause are new in Clojure in the 1.10 prerelease builds, although they’ve been in ClojureScript for a while. So they’re not portable for pre-1.10 Clojure versions.