Skip to content

Instantly share code, notes, and snippets.

@rveitch
Last active June 24, 2024 18:34
Show Gist options
  • Save rveitch/46b3a7344b3d778ff666b2dac271206c to your computer and use it in GitHub Desktop.
Save rveitch/46b3a7344b3d778ff666b2dac271206c to your computer and use it in GitHub Desktop.
Node Custom Errors Examples
// REFERENCE: https://gist.github.com/slavafomin/b164e3e710a6fc9352c934b9073e7216
const generateMessage = (message, code, subcode) => {
let errorCoding = '';
if (code) errorCoding = `Code: ${code}`;
if (subcode) errorCoding = `${errorCoding} Subcode: ${subcode}`;
return `${message} ${errorCoding}`;
};
class CustomError extends Error {
constructor(message, code, subcode) {
// Calling parent constructor of base Error class.
super(generateMessage(message, code, subcode));
// Saving class name in the property of our custom error as a shortcut.
this.name = this.constructor.name;
// Capturing stack trace, excluding constructor call from it.
Error.captureStackTrace(this, this.constructor);
// Additional custom properties you want.
if (code) {
this.code = code;
}
if (subcode) {
this.subcode = subcode;
}
}
}
class MailchimpError extends CustomError {
constructor(message, code, subcode) {
const defaultMessage = 'Unknown MailChimp Error';
const defaultCode = 400;
const defaultSubcode = 500;
super((message || defaultMessage), (code || defaultCode), (subcode || defaultSubcode));
this.feature = 'mailchimp';
this.team = 'integration';
this.helpDocLink = 'https://help.example.com/help-article';
}
}
/**
* This is an example of the base error handler
*/
try {
throw new CustomError('It went bad!', 1234, 5678);
} catch (err) {
if (err instanceof CustomError) {
console.log('Custom error occurred!', err);
} else {
console.log('Unknown error', err);
}
}
/**
* Here's an example of how you can use the base error handler to add "service specific" or "feature level" logging
*/
try {
throw new MailchimpError('Chimps died!');
} catch (err) {
if (err instanceof MailchimpError) {
console.log('MailChimp error occurred!', err);
} else {
console.log('Unknown error', err);
}
}
@rveitch
Copy link
Author

rveitch commented Sep 16, 2020

Example output:
image

Runkit Example:
https://runkit.com/rveitch/5f625431d59540001ab3bef5

@rveitch
Copy link
Author

rveitch commented Sep 22, 2020

Priority level can also be added. Team and Feature are probably not necessary and bad long term as those can change but it's just an example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment