Last active
December 31, 2017 10:24
-
-
Save normancarcamo/cffd8217ef1d8d689451dfab2d90d52c to your computer and use it in GitHub Desktop.
Custom error builder in 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
export function BuildError(object) { | |
// Throw an error if the 'object' param doesn't pass the follow rules: | |
// 1. If the object param is not an object | |
// 2. If the object param doesn't include a property 'message' | |
// 3. If the object param includes the property 'message' but is not of string type | |
// 4. If the object param includes the property 'message' but it is empty | |
if (!object.hasOwnProperty('message') || typeof object.message !== 'string') { | |
throw new Error('Error when trying to build a new error'); | |
} | |
// As everything is ok, we proceed to create a new Error using the message: | |
let error = new Error(object.message); | |
// As we've got the custom error we need to check if there are more properties: | |
Object.keys(object).reduce((source, key) => { | |
// As we already have the property 'message' in out custom error we just skip it and we continue adding the rest of them: | |
if (key !== 'message') { | |
source[key] = object[key]; | |
} | |
// Return the error with all the custom properties: | |
return error; | |
}, error); | |
// Return the error: | |
return error; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment