Exception handling is always an important topic. This presentation will provide couple of good practices to deal with Errors & Exceptions happing in Node.js.
Keep those in mind, you will write a better code for a more stable software.
Happy Coding!
2. Node.js
• is a still a relatively new programming language
• Node.js crashes for any ‘uncatch error’
• Most developers are confused when to use
• try/catch
• pass error to a callback
• throw an error
3. error vs. exception
• an error = an instance of the Error class
• can be created
• can be thrown
• can passed to callback
• a thrown error = an Exception
4. errors
Operational Errors
(run-time issue, not bug)
Programmer Errors
(bug)
• out-of-memory
• connection issues
• timeout
• server return 500 HTTP code
• socket hang-up
• no ‘undefined’ check
• no callback for asynchronous
function
• object type error
a correct code must be able to deal with operation error
5. Best Practices for dealing
with operation errors
• Always put asynchronous code into try/catch (otherwise Node.js
crashes if uncaught error happens)
• Synchronous code: return error.
• ENONT error why trying to open a file: create file the first before read it
• socket hang-up: write code to reconnect if needed
• ready to deal with invalid JSON - using try/catch
• retry with 5xx HTTP error
• no idea how to deal with unthinkable/-solvable issue - such as
ENOMEM: log the error and crash (intentionally)
6. Dealing with programmer
errors
• crash immediately
• how: throw new Error(‘ehh’);
…. if you have a restarter in place (like Bluemix)
…. or just use: forever.js
7. • instead of ‘callback(result)’ use ‘callback(err,
result)’
• because: either ‘result’ or ‘err’ is NULL!
8. Error class
• has {name, message, stack}
• if you create an Error instance manually, at least
provide {name, message}
9. last chance…
• use process.on(‘uncaughtException’, function()
{<do_sth>}); —> Global Catch
• it’s NOT recommended…but what if your app’s
just crashed without leaving a trace?
10. Automated Test
• Crucially important
• start with unit-test for all modules
• then integration test
• no test, no CI, you are in the coding hell!