Last active
June 5, 2019 13:34
-
-
Save AndersDJohnson/4415030 to your computer and use it in GitHub Desktop.
Using Custom Errors in Node.js
This file contains hidden or 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
| /** | |
| * Using Custom Errors in Node.js | |
| * http://dustinsenos.com/articles/customErrorsInNode | |
| */ | |
| // Grab the util module that's bundled with Node | |
| var util = require('util') | |
| // Create a new Abstract Error constructor | |
| var AbstractError = function (msg, constr) { | |
| // If defined, pass the constr property to V8's | |
| // captureStackTrace to clean up the output | |
| Error.captureStackTrace(this, constr || this) | |
| // If defined, store a custom error message | |
| this.message = msg || 'Error' | |
| } | |
| // Extend our AbstractError from Error | |
| util.inherits(AbstractError, Error) | |
| // Give our Abstract error a name property. Helpful for logging the error later. | |
| AbstractError.prototype.name = 'Abstract Error' | |
| /** | |
| * Database Error | |
| * Now that we have an AbstractError class, we can extend it with other custom error classes as we see fit: | |
| */ | |
| var DatabaseError = function (msg) { | |
| DatabaseError.super_.call(this, msg, this.constructor) | |
| } | |
| util.inherits(DatabaseError, AbstractError) | |
| DatabaseError.prototype.message = 'Database Error' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment