Skip to content

Commit

Permalink
feat: errorCode option for ensure* utils
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Mar 8, 2021
1 parent fc6c092 commit 777a1f2
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -67,6 +67,7 @@ Each `*/ensure` utility, accepts following options (eventually passed with secon
- `errorMessage` - Custom error message. Following placeholders can be used:
- `%v` - To be replaced with short string representation of invalid value
- `%n` - To be replaced with meaninfgul name (to be passed with `name` option) of validated value. Not effective if `name` option is not present
- `errorCode` - Eventual error code to be exposed on `.code` error property
- `name` - Meaningful name for validated value, to be used in error message, assuming it contains `%n` placeholder
- `Error` - Alternative error constructor to be used (defaults to `TypeError`)

Expand Down
4 changes: 3 additions & 1 deletion lib/resolve-exception.js
Expand Up @@ -9,5 +9,7 @@ module.exports = function (value, defaultMessage, inputOptions) {
if (inputOptions.isOptional) return null;
}
var ErrorConstructor = (inputOptions && inputOptions.Error) || TypeError;
throw new ErrorConstructor(resolveErrorMessage(defaultMessage, value, inputOptions));
var error = new ErrorConstructor(resolveErrorMessage(defaultMessage, value, inputOptions));
if (inputOptions && inputOptions.errorCode) error.code = inputOptions.errorCode;
throw error;
};
8 changes: 8 additions & 0 deletions test/lib/resolve-exception.js
Expand Up @@ -37,4 +37,12 @@ describe("lib/handle-exception", function () {
assert.equal(error.message, "Invalid value");
}
});
it("Should support error code option", function () {
try {
handleException(12, "Invalid value", { errorCode: "SOME_CODE" });
throw new Error("Unexpected");
} catch (error) {
assert.equal(error.code, "SOME_CODE");
}
});
});

0 comments on commit 777a1f2

Please sign in to comment.