Organising NodeJS' Error Handling Hell with IcedCoffeeScript
Let’s suppose you are building a NodeJS application. Lets focus on only one request (let it be our custom authentication despite of the fact that there are ready to use modules such as Passport). After you handled all edge cases your code may look like this:
It looks quite deep. We can make it less deep by joining all if/else statements into one big if/else-if/else block:
Now this is much better, but still there is room for improvement. Lets add following function:
Now we can rewrite our previous code to:
This looks much better then what we have at the beginning. But can we do even better? Yes we can! Let’s use the power of ice (or simply IcedCoffeeScript). By awaiting the findOne user callback we can change our previous code into this piece of beauty:
This way we shortened our code more then 2 times, changed maximal level of code depth from 7 to 2 thus making the code much more beautiful, readable and maintainable.