flocore/lib/util/preconditions.js
Esteban Ordano ea17a6ace1 Add a preconditions module, and refactor errors
100% code coverage for the preconditions module.

Usage:
```
$.checkState(something === anotherthing, 'Expected something to be
anotherthing');
$.checkArgument(something < 100, 'something', 'must be less than 100');
$.checkArgumentType(something, PrivateKey, 'something'); // The third
argument is a helper to mention the name of the argument
$.checkArgumentType(something, PrivateKey); // but it's optional (will
show up as "(unknown argument)")
```
2014-12-10 11:56:38 -03:00

30 lines
800 B
JavaScript

'use strict';
var errors = require('../errors');
var _ = require('lodash');
module.exports = {
checkState: function(condition, message) {
if (!condition) {
throw new errors.InvalidState(message);
}
},
checkArgument: function(condition, argumentName, message) {
if (!condition) {
throw new errors.InvalidArgument(argumentName, message);
}
},
checkArgumentType: function(argument, type, argumentName) {
argumentName = argumentName || '(unknown name)';
if (_.isString(type)) {
if (typeof argument !== type) {
throw new errors.InvalidArgumentType(argument, type, argumentName);
}
} else {
if (!(argument instanceof type)) {
throw new errors.InvalidArgumentType(argument, type.name, argumentName);
}
}
}
};