Created
June 21, 2018 06:16
-
-
Save gsrai/c2ff6f7f30c156a3417eb28e0403ec34 to your computer and use it in GitHub Desktop.
Creating, throwing and handling exceptions in JS
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
function InvalidRequestError(statusCode, message) { | |
const defaultMessage = 'invalid request, status code ' + statusCode; | |
this.name = 'InvalidRequestError'; | |
this.message = message || defaultMessage; | |
this.stack = (new Error()).stack; | |
} | |
InvalidRequestError.prototype = Object.create(Error.prototype); | |
InvalidRequestError.prototype.constructor = InvalidRequestError; | |
function someRequest(statusCode) { | |
if(statusCode === '500' || statusCode === '400') { | |
throw new InvalidRequestError(statusCode); | |
} | |
return statusCode; | |
} | |
function main() { | |
try { | |
someRequest('400'); | |
} catch(e) { | |
// can check type of error here for individual handlers. | |
console.error(e.name); | |
console.error(e.message); | |
console.error(e.stack); | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment