node.js exception handling
DESCRIPTION
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!TRANSCRIPT
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
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
errorsOperational 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
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)
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
• instead of ‘callback(result)’ use ‘callback(err, result)’
• because: either ‘result’ or ‘err’ is NULL!
Error class
• has {name, message, stack}
• if you create an Error instance manually, at least provide {name, message}
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?
Automated Test
• Crucially important
• start with unit-test for all modules
• then integration test
• no test, no CI, you are in the coding hell!
and … think about this
Function - write it the right way -
• first argument ist error
• last ist callback
• use return (return callback(null, data); or return(err)
Sources• Error Handling in Node.js https://
www.joyent.com/developers/node/design/errors
• Node.js Best Practices: http://www.slideshare.net/the_undefined/nodejs-best-practices-10428790
• Continuous Development: http://blog.risingstack.com/continuous-deployment-of-node-js-applications/
–Philip Sidney
“Either I will find a way,or I will make one”