Skip to content

Instantly share code, notes, and snippets.

@gsrai
Created June 21, 2018 06:16
Show Gist options
  • Save gsrai/c2ff6f7f30c156a3417eb28e0403ec34 to your computer and use it in GitHub Desktop.
Save gsrai/c2ff6f7f30c156a3417eb28e0403ec34 to your computer and use it in GitHub Desktop.
Creating, throwing and handling exceptions in JS
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