Last active
April 9, 2017 17:37
-
-
Save justin-nodeboy/47f199ad113194f5a6fa9de1a2d45005 to your computer and use it in GitHub Desktop.
Custom Error using ES6 Javascript
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
class CustomError extends Error { | |
//Extend the super class, in this case the standard Error object | |
constructor(message){ | |
super(message); | |
this.name = this.constructor.name; | |
} | |
} | |
module.exports = CustomError; |
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
//Include the custom error using require | |
const CustomError = require('./CustomError'); | |
class UseError { | |
constructor(obj){ | |
if (!obj.hasOwnProperty('name')){ | |
//Throw the error like you would normally | |
throw new CustomError("A name is required"); | |
} else if (typeof obj.name != "string"){ | |
throw new CustomError("The name must be a string"); | |
} else { | |
this.name = obj.name; | |
} | |
} | |
} | |
module.exports = UseError; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment