Last active
January 6, 2017 02:11
-
-
Save skinnyjames/b3007193459367c8072a723a7fd4453d to your computer and use it in GitHub Desktop.
Custom Error Handling in Node with Promises
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
module.exports = { | |
ValidationError: class extends Error{ | |
constructor(message){ | |
super(message || "This input is invalid") | |
} | |
}, | |
DatabaseError: class extends Error { | |
constructor(message){ | |
super(message || "The database call failed") | |
} | |
}, | |
OtherError: class extends Error { | |
constructor(message){ | |
super(message || "Something else happened") | |
} | |
} | |
}; |
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
const Promise = require("bluebird"); | |
const fs = require('fs'); | |
const e = require('./application-errors'); | |
Promise.promisifyAll(fs); | |
function processNewlines(data){ | |
console.log(data.split('\n').length - 1); | |
return Promise.reject(new e.ValidationError("processNewlines broke!")); | |
} | |
fs.readFileAsync(process.argv[2], 'utf8') | |
.then(processNewlines) | |
.catch( e.ValidationError, function(e){ | |
console.error(e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment