Skip to content

Instantly share code, notes, and snippets.

@AndersDJohnson
Last active June 5, 2019 13:34
Show Gist options
  • Select an option

  • Save AndersDJohnson/4415030 to your computer and use it in GitHub Desktop.

Select an option

Save AndersDJohnson/4415030 to your computer and use it in GitHub Desktop.
Using Custom Errors in Node.js
/**
* 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