Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short notation for coffeescript try/catch

Tags:

I sometimes write code like:

try doSomething() catch e   handleError e 

which is not what nice and clean coffeescript code should look like.

Is there a way to write:

try doSomething() catch e handleError e   #<-- will not compile 

This would save me about 33% of the lines of code in my try/catch statements ;)

like image 679
Juve Avatar asked Aug 25 '13 09:08

Juve


People also ask

How do you write a CoffeeScript?

In general, we use parenthesis while declaring the function, calling it, and also to separate the code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while creating functions, we use an arrow mark (->) instead of parentheses as shown below.

Is CoffeeScript still a thing?

As of today, January 2020, CoffeeScript is completely dead on the market (though the GitHub repository is still kind of alive).

How do I use CoffeeScript in HTML?

If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.

How do I know if CoffeeScript is installed?

The coffee and cake commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so. This allows different versions of CoffeeScript to be installed globally and locally.


2 Answers

Writing try/catch one-liners works like if-then one-liners or loop one-liners using the then keyword:

try doSomething() catch e then handleError e finally cleanUp() 

You can even have it on a single line if you like:

try doSomething() catch e then handleError e finally cleanUp() 
like image 188
Juve Avatar answered Sep 17 '22 21:09

Juve


Cross-posting from https://github.com/jashkenas/coffeescript/issues/2413:

FWIW, I discovered you can write

try    compute something catch error     handle error  unless error?     handle success 

This is possible since CS puts the variable of the catch clause into the surrounding scope, which JS does not do. One might even argue that saying unless error? is clearer than both else (this is not an if clause) and continue (this is not a loop) in that position.

People who insist on oneliners can even write

try compute something catch error then handle error unless error? then handle success 

which is somewhat cool and somewhat unreadable.

A finally clause would have to go before the unless, of course.

like image 43
John Frazer Avatar answered Sep 20 '22 21:09

John Frazer