Skip to content

Instantly share code, notes, and snippets.

@akirattii
Last active November 27, 2017 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/3769b3938b1ad6d48cf27025fc5107fa to your computer and use it in GitHub Desktop.
Save akirattii/3769b3938b1ad6d48cf27025fc5107fa to your computer and use it in GitHub Desktop.
Example: How to make some error classes extended Error object.
const {
AppError,
HogeError,
FooError,
} = require("./AppError.js");
try {
throw new HogeError("HogeError occurred");
} catch (e) {
if (e instanceof HogeError) {
console.log(`${e.name} caught!: "${e.message}"`);
}
}
try {
throw new FooError("FooError happened");
} catch (e) {
if (e instanceof FooError) {
console.log(`${e.name} caught!: "${e.message}"`);
}
}
/** application error base */
module.exports.AppError = class AppError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name
Error.captureStackTrace(this, this.constructor);
}
};
//
// Derived application errors
//
module.exports.HogeError = class HogeError extends this.AppError {
constructor(message) {
super(message);
}
};
module.exports.FooError = class FooError extends this.AppError {
constructor(message) {
super(message);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment