Last active
November 27, 2017 10:56
-
-
Save akirattii/3769b3938b1ad6d48cf27025fc5107fa to your computer and use it in GitHub Desktop.
Example: How to make some error classes extended Error object.
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 { | |
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}"`); | |
} | |
} | |
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
/** 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