Created
February 19, 2015 21:58
-
-
Save oprearocks/fac301833af8bcb2b8d5 to your computer and use it in GitHub Desktop.
Error handling in promise-based logic -- when to process.exit and when not to
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In NodeJS I usually have this in it's own module, and use module.exports to expose it. | |
var errors = { | |
failure : { | |
action : function(error) { | |
// Handle error and set some defaults | |
console.warn('FAILURE: ' + error.message); // process.stdout.write(error.message); | |
} | |
}, | |
fatal : { | |
action : function(error) { | |
// Die! | |
console.error('FATAL: ' + error.message); // process.stdout.write(error.message); | |
// process.exit(1); | |
} | |
} | |
}; | |
function asyncmethod(config) { | |
var deferred = Promise.defer(); | |
setTimeout(function() { | |
if (config.success) { | |
deferred.resolve('We have data.'); | |
} else if (config.fail) { | |
deferred.reject({ | |
type: 'failure', | |
message: 'Something went wrong with the query.\nCatch this and move on', | |
statusCode: 200 | |
}); | |
} else { | |
deferred.reject({ | |
type: 'fatal', | |
message : 'This is totally wrong! \nCrash the process.', | |
statusCode: 500 | |
}); | |
} | |
}, 2000); | |
return deferred.promise; | |
} | |
// Call | |
asyncmethod({ | |
//change 'fatal' with 'fail' or 'success' | |
fail: true | |
}).then(function(data) { | |
console.info('SUCCESS: ' + data); | |
}).catch(function(error) { | |
errors[error.type].action(error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment