refactor: switch to template strings for errors.

This commit is contained in:
Christopher Jeffrey 2017-07-01 04:34:04 -07:00
parent 7932a25abe
commit 3af014119a
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
34 changed files with 110 additions and 109 deletions

View File

@ -161,10 +161,10 @@ PaymentRequest.prototype.getAlgorithm = function getAlgorithm() {
throw new Error('Could not parse PKI algorithm.');
if (parts[0] !== 'x509')
throw new Error('Unknown PKI type: ' + parts[0]);
throw new Error(`Unknown PKI type: ${parts[0]}.`);
if (parts[1] !== 'sha1' && parts[1] !== 'sha256')
throw new Error('Unknown hash algorithm: ' + parts[1]);
throw new Error(`Unknown hash algorithm: ${parts[1]}.`);
return new Algorithm(parts[0], parts[1]);
};

View File

@ -189,7 +189,7 @@ x509.getKeyAlgorithm = function getKeyAlgorithm(cert) {
let alg = x509.oid[oid];
if (!alg)
throw new Error('Unknown key algorithm: ' + oid);
throw new Error(`Unknown key algorithm: ${oid}.`);
return alg;
};
@ -205,7 +205,7 @@ x509.getSigAlgorithm = function getSigAlgorithm(cert) {
let alg = x509.oid[oid];
if (!alg || !alg.hash)
throw new Error('Unknown signature algorithm: ' + oid);
throw new Error(`Unknown signature algorithm: ${oid}.`);
return alg;
};
@ -228,7 +228,7 @@ x509.getCurve = function getCurve(params) {
curve = x509.curves[oid];
if (!curve)
throw new Error('Unknown ECDSA curve: ' + oid);
throw new Error(`Unknown ECDSA curve: ${oid}.`);
return curve;
};
@ -457,7 +457,7 @@ x509.verifyChain = function verifyChain(certs) {
let sig = child.sig;
if (!pk.verify(alg.hash, msg, sig, key))
throw new Error(alg.key + ' verification failed for chain.');
throw new Error(`${alg.key} verification failed for chain.`);
}
// Make sure we trust one

View File

@ -712,7 +712,7 @@ ChainDB.prototype.prune = async function prune(tip) {
let hash = await this.getHash(i);
if (!hash)
throw new Error('Cannot find hash for ' + i);
throw new Error(`Cannot find hash for ${i}.`);
batch.del(layout.b(hash));
batch.del(layout.u(hash));

View File

@ -120,7 +120,7 @@ Amount.prototype.to = function to(unit, num) {
case 'btc':
return this.toBTC(num);
}
throw new Error('Unknown unit "' + unit + '".');
throw new Error(`Unknown unit "${unit}".`);
};
/**
@ -218,7 +218,7 @@ Amount.prototype.from = function from(unit, value, num) {
case 'btc':
return this.fromBTC(value, num);
}
throw new Error('Unknown unit "' + unit + '".');
throw new Error(`Unknown unit "${unit}".`);
};
/**

View File

@ -98,6 +98,6 @@ function getHash(name) {
case 'sha512':
return 'SHA-512';
default:
throw new Error('Algorithm not supported: ' + name);
throw new Error(`Algorithm not supported: ${name}.`);
}
}

View File

@ -18,11 +18,11 @@ exports.get = function get(name) {
case 'memory':
return require('./memdb');
default:
throw new Error('Database backend "' + name + '" not found.');
throw new Error(`Database backend "${name}" not found.`);
}
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND')
throw new Error('Database backend "' + name + '" not found.');
throw new Error(`Database backend "${name}" not found.`);
throw e;
}
};

View File

@ -25,6 +25,6 @@ exports.get = function get(name) {
case 'spanish':
return words.spanish;
default:
throw new Error('Unknown language: ' + name);
throw new Error(`Unknown language: ${name}.`);
}
};

View File

@ -23,6 +23,6 @@ exports.get = function get(name) {
case 'spanish':
return require('./words/spanish.js');
default:
throw new Error('Unknown language: ' + name);
throw new Error(`Unknown language: ${name}.`);
}
};

View File

@ -68,10 +68,9 @@ HTTPBase.prototype._init = function _init() {
this.server.on('connection', (socket) => {
socket.on('error', (err) => {
if (err.message === 'Parse Error') {
let msg = 'http_parser.execute failure (';
msg += 'parsed=' + (err.bytesParsed || -1);
msg += ' code=' + err.code;
msg += ')';
let msg = 'http_parser.execute failure';
msg += ` (parsed=${err.bytesParsed || -1}`;
msg += ` code=${err.code})`;
err = new Error(msg);
}
@ -134,7 +133,7 @@ HTTPBase.prototype.handleRequest = async function handleRequest(req, res) {
routes = this.routes.getHandlers(req.method);
if (!routes)
throw new Error('No routes found for method: ' + req.method);
throw new Error(`No routes found for method: ${req.method}.`);
for (let route of routes) {
let params = route.match(req.pathname);
@ -151,7 +150,7 @@ HTTPBase.prototype.handleRequest = async function handleRequest(req, res) {
return;
}
throw new Error('No routes found for path: ' + req.pathname);
throw new Error(`No routes found for path: ${req.pathname}.`);
};
/**

View File

@ -602,7 +602,7 @@ function getType(type) {
case 'bin':
return 'application/octet-stream';
default:
throw new Error('Unknown type: ' + type);
throw new Error(`Unknown type: ${type}.`);
}
}

View File

@ -1355,7 +1355,7 @@ RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinb
if (!deploy.force) {
if (!rules || rules.indexOf(name) === -1) {
throw new RPCError(errs.INVALID_PARAMETER,
'Client must support ' + name + '.');
`Client must support ${name}.`);
}
name = '!' + name;
}
@ -2398,7 +2398,7 @@ RPC.prototype._addBlock = async function _addBlock(block) {
if (err.type === 'VerifyError') {
this.logger.warning('RPC block rejected: %s (%s).',
block.rhash(), err.reason);
return 'rejected: ' + err.reason;
return `rejected: ${err.reason}`;
}
throw err;
}

View File

@ -253,7 +253,7 @@ RPCBase.prototype.execute = async function execute(json, help) {
return await mount.execute(json, help);
}
throw new RPCError(RPCBase.errors.METHOD_NOT_FOUND,
'Method not found: ' + json.method + '.');
`Method not found: ${json.method}.`);
}
return await func.call(this, json.params, help);

View File

@ -8,6 +8,7 @@
'use strict';
const assert = require('assert');
const path = require('path');
const HTTPBase = require('./base');
const util = require('../utils/util');
const base58 = require('../utils/base58');
@ -774,8 +775,8 @@ HTTPOptions.prototype.fromOptions = function fromOptions(options) {
if (options.prefix != null) {
assert(typeof options.prefix === 'string');
this.prefix = options.prefix;
this.keyFile = this.prefix + '/key.pem';
this.certFile = this.prefix + '/cert.pem';
this.keyFile = path.join(this.prefix, 'key.pem');
this.certFile = path.join(this.prefix, 'cert.pem');
}
if (options.host != null) {

View File

@ -7,6 +7,7 @@
'use strict';
const assert = require('assert');
const path = require('path');
const AsyncObject = require('../utils/asyncobject');
const common = require('../blockchain/common');
const policy = require('../protocol/policy');
@ -2057,7 +2058,7 @@ MempoolOptions.prototype.fromOptions = function fromOptions(options) {
if (options.prefix != null) {
assert(typeof options.prefix === 'string');
this.prefix = options.prefix;
this.location = this.prefix + '/mempool';
this.location = path.join(this.prefix, 'mempool');
}
if (options.location != null) {

View File

@ -417,7 +417,7 @@ BIP150.prototype._wait = function wait(timeout, resolve, reject) {
this.job = co.job(resolve, reject);
if (this.outbound && !this.peerIdentity) {
this.reject(new Error('No identity for ' + this.hostname + '.'));
this.reject(new Error(`No identity for ${this.hostname}.`));
return;
}
@ -729,7 +729,7 @@ AuthDB.prototype.parseKnown = function parseKnown(text) {
key = Buffer.from(key, 'hex');
if (key.length !== 33)
throw new Error('Invalid key: ' + parts[1]);
throw new Error(`Invalid key: ${parts[1]}.`);
if (host && host.length > 0)
this.addKnown(host, key);
@ -792,7 +792,7 @@ AuthDB.prototype.parseAuth = function parseAuth(text) {
key = Buffer.from(line, 'hex');
if (key.length !== 33)
throw new Error('Invalid key: ' + line);
throw new Error(`Invalid key: ${line}.`);
this.addAuthorized(key);
}

View File

@ -134,7 +134,7 @@ exports.REQUIRED_SERVICES = 0
* @default
*/
exports.USER_AGENT = '/bcoin:' + pkg.version + '/';
exports.USER_AGENT = `/bcoin:${pkg.version}/`;
/**
* Max message size (~4mb with segwit, formerly 2mb)

View File

@ -1419,10 +1419,10 @@ Peer.prototype.error = function error(err) {
msg = err.code;
err = new Error(msg);
err.code = msg;
err.message = 'Socket Error: ' + msg;
err.message = `Socket Error: ${msg}`;
}
err.message += ' (' + this.hostname() + ')';
err.message += ` (${this.hostname()})`;
this.emit('error', err);
};

View File

@ -735,7 +735,7 @@ function parseAddr(data, offset) {
port = br.readU16BE();
break;
default:
throw new Error('Unknown SOCKS address type: ' + type + '.');
throw new Error(`Unknown SOCKS address type: ${type}.`);
}
return {

View File

@ -688,7 +688,7 @@ function findError(el) {
if (cdesc)
desc = cdesc.text;
return new Error('UPnPError: ' + desc + ' (' + code + ')');
return new Error(`UPnPError: ${desc} (${code}).`);
}
/*

View File

@ -259,7 +259,7 @@ Config.prototype.str = function str(key, fallback) {
return fallback;
if (typeof value !== 'string')
throw new Error(key + ' must be a string.');
throw new Error(`${key} must be a string.`);
return value;
};
@ -282,17 +282,17 @@ Config.prototype.num = function num(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'number')
throw new Error(key + ' must be a positive integer.');
throw new Error(`${key} must be a positive integer.`);
return value;
}
if (!/^\d+$/.test(value))
throw new Error(key + ' must be a positive integer.');
throw new Error(`${key} must be a positive integer.`);
value = parseInt(value, 10);
if (!isFinite(value))
throw new Error(key + ' must be a positive integer.');
throw new Error(`${key} must be a positive integer.`);
return value;
};
@ -315,17 +315,17 @@ Config.prototype.flt = function flt(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'number')
throw new Error(key + ' must be a float.');
throw new Error(`${key} must be a float.`);
return value;
}
if (!/^\d*(?:\.\d*)?$/.test(value))
throw new Error(key + ' must be a float.');
throw new Error(`${key} must be a float.`);
value = parseFloat(value);
if (!isFinite(value))
throw new Error(key + ' must be a float.');
throw new Error(`${key} must be a float.`);
return value;
};
@ -348,22 +348,22 @@ Config.prototype.amt = function amt(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'number')
throw new Error(key + ' must be an amount.');
throw new Error(`${key} must be an amount.`);
return value;
}
if (!/^\d+(\.\d{0,8})?$/.test(value))
throw new Error(key + ' must be an amount.');
throw new Error(`${key} must be an amount.`);
value = parseFloat(value);
if (!isFinite(value))
throw new Error(key + ' must be an amount.');
throw new Error(`${key} must be an amount.`);
value *= 1e8;
if (value % 1 !== 0 || value < 0 || value > 0x1fffffffffffff)
throw new Error(key + ' must be an amount (uint64).');
throw new Error(`${key} must be an amount (uint64).`);
return value;
};
@ -386,7 +386,7 @@ Config.prototype.bool = function bool(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'boolean')
throw new Error(key + ' must be a boolean.');
throw new Error(`${key} must be a boolean.`);
return value;
}
@ -396,7 +396,7 @@ Config.prototype.bool = function bool(key, fallback) {
if (value === 'false' || value === '0')
return false;
throw new Error(key + ' must be a boolean.');
throw new Error(`${key} must be a boolean.`);
};
/**
@ -418,14 +418,14 @@ Config.prototype.buf = function buf(key, fallback) {
if (typeof value !== 'string') {
if (!Buffer.isBuffer(value))
throw new Error(key + ' must be a buffer.');
throw new Error(`${key} must be a buffer.`);
return value;
}
data = Buffer.from(value, 'hex');
if (data.length !== value.length / 2)
throw new Error(key + ' must be a hex string.');
throw new Error(`${key} must be a hex string.`);
return data;
};
@ -449,7 +449,7 @@ Config.prototype.array = function array(key, fallback) {
if (typeof value !== 'string') {
if (!Array.isArray(value))
throw new Error(key + ' must be an array.');
throw new Error(`${key} must be an array.`);
return value;
}
@ -483,7 +483,7 @@ Config.prototype.obj = function obj(key, fallback) {
return fallback;
if (!value || typeof value !== 'object')
throw new Error(key + ' must be an object.');
throw new Error(`${key} must be an object.`);
return value;
};
@ -505,7 +505,7 @@ Config.prototype.func = function func(key, fallback) {
return fallback;
if (!value || typeof value !== 'function')
throw new Error(key + ' must be a function.');
throw new Error(`${key} must be a function.`);
return value;
};

View File

@ -298,11 +298,11 @@ Node.prototype.use = function use(plugin) {
case 'mempool':
case 'miner':
case 'pool':
assert(false, plugin.id + ' is already added.');
assert(false, `${plugin.id} is already added.`);
break;
}
assert(!this.plugins[plugin.id], plugin.id + ' is already added.');
assert(!this.plugins[plugin.id], `${plugin.id} is already added.`);
this.plugins[plugin.id] = instance;
}
@ -355,7 +355,7 @@ Node.prototype.require = function require(name) {
}
plugin = this.plugins[name];
assert(plugin, name + ' is not loaded.');
assert(plugin, `${name} is not loaded.`);
return plugin;
};

View File

@ -1597,7 +1597,7 @@ CoinSelector.prototype.init = function init(coins) {
this.coins.sort(sortValue);
break;
default:
throw new FundingError('Bad selection type: ' + this.selection);
throw new FundingError(`Bad selection type: ${this.selection}.`);
}
};
@ -1812,8 +1812,8 @@ function FundingError(msg, available, required) {
this.requiredFunds = -1;
if (available != null) {
this.message += ' (available=' + Amount.btc(available) + ',';
this.message += ' required=' + Amount.btc(required) + ')';
this.message += ` (available=${Amount.btc(available)},`;
this.message += ` required=${Amount.btc(required)})`;
this.availableFunds = available;
this.requiredFunds = required;
}

View File

@ -245,7 +245,7 @@ Network.by = function by(value, compare, network, name) {
network = Network.get(network);
if (compare(network, value))
return network;
throw new Error('Network mismatch for ' + name + '.');
throw new Error(`Network mismatch for ${name}.`);
}
for (let type of networks.types) {
@ -254,7 +254,7 @@ Network.by = function by(value, compare, network, name) {
return Network.get(type);
}
throw new Error('Network not found for ' + name + '.');
throw new Error(`Network not found for ${name}.`);
};
/**
@ -360,7 +360,7 @@ Network.prototype.toString = function toString() {
*/
Network.prototype.inspect = function inspect() {
return '<Network: ' + this.type + '>';
return `<Network: ${this.type}>`;
};
/**

View File

@ -154,7 +154,7 @@ ScriptNum.prototype.toString = function toString(base) {
return str;
}
assert(false, 'Base ' + base + ' not supported.');
assert(false, `Base ${base} not supported.`);
};
ScriptNum.prototype.toJSON = function toJSON() {
@ -236,7 +236,7 @@ ScriptNum.prototype.fromString = function fromString(str, base) {
return this;
}
assert(false, 'Base ' + base + ' not supported.');
assert(false, `Base ${base} not supported.`);
};
ScriptNum.fromString = function fromString(str, base) {

View File

@ -127,7 +127,7 @@ ASN1.readSeq = function readSeq(br) {
ASN1.implicit = function implicit(br, type) {
let tag = ASN1.readTag(br);
if (tag.type !== type)
throw new Error('Unexpected tag: ' + tag.type + '.');
throw new Error(`Unexpected tag: ${tag.type}.`);
return tag;
};
@ -232,7 +232,7 @@ ASN1.readString = function readString(br) {
case 0x1e: // bmpstr
return br.readString('utf8', tag.size);
default:
throw new Error('Unexpected tag: ' + tag.type + '.');
throw new Error(`Unexpected tag: ${tag.type}.`);
}
};
@ -393,7 +393,7 @@ ASN1.readTime = function readTime(br) {
sec = str.slice(12, 14) | 0;
break;
default:
throw new Error('Unexpected tag: ' + tag.type + '.');
throw new Error(`Unexpected tag: ${tag.type}.`);
}
return Date.UTC(year, mon - 1, day, hour, min, sec, 0) / 1000;

View File

@ -235,7 +235,7 @@ AsyncEmitter.prototype.emit = function emit(type) {
if (error instanceof Error)
throw error;
err = new Error('Uncaught, unspecified "error" event. (' + error + ')');
err = new Error(`Uncaught, unspecified "error" event. (${error})`);
err.context = error;
throw err;
}
@ -298,7 +298,7 @@ AsyncEmitter.prototype.fire = async function fire(type) {
if (error instanceof Error)
throw error;
err = new Error('Uncaught, unspecified "error" event. (' + error + ')');
err = new Error(`Uncaught, unspecified "error" event. (${error})`);
err.context = error;
throw err;
}

View File

@ -165,7 +165,7 @@ function callbackify(func) {
if (args.length === 0
|| typeof args[args.length - 1] !== 'function') {
throw new Error((func.name || 'Function') + ' requires a callback.');
throw new Error(`${func.name || 'Function'} requires a callback.`);
}
callback = args.pop();

View File

@ -1037,7 +1037,7 @@ encoding.EncodingError = function EncodingError(offset, reason) {
Error.captureStackTrace(this, EncodingError);
this.type = 'EncodingError';
this.message = reason + ' (offset=' + offset + ').';
this.message = `${reason} (offset=${offset}).`;
};
inherits(encoding.EncodingError, Error);

View File

@ -440,7 +440,7 @@ IP.toString = function toString(raw) {
return host;
}
throw new Error('Invalid IP address: ' + raw.toString('hex'));
throw new Error(`Invalid IP address: ${raw.toString('hex')}.`);
};
/**

View File

@ -87,7 +87,7 @@ Validator.prototype.get = function get(key, fallback) {
let value;
if (!map || typeof map !== 'object')
throw new ValidationError('Data is not an object.');
throw new ValidationError('data', 'object');
value = map[key];
@ -115,7 +115,7 @@ Validator.prototype.str = function str(key, fallback) {
return fallback;
if (typeof value !== 'string')
throw new ValidationError(fmt(key) + ' must be a string.');
throw new ValidationError(key, 'number');
return value;
};
@ -138,17 +138,17 @@ Validator.prototype.num = function num(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'number')
throw new ValidationError(fmt(key) + ' must be a number.');
throw new ValidationError(key, 'number');
return value;
}
if (!/^\d+$/.test(value))
throw new ValidationError(fmt(key) + ' must be a number.');
throw new ValidationError(key, 'number');
value = parseInt(value, 10);
if (!isFinite(value))
throw new ValidationError(fmt(key) + ' must be a number.');
throw new ValidationError(key, 'number');
return value;
};
@ -171,17 +171,17 @@ Validator.prototype.flt = function flt(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'number')
throw new ValidationError(fmt(key) + ' must be a float.');
throw new ValidationError(key, 'float');
return value;
}
if (!/^\d*(?:\.\d*)?$/.test(value))
throw new ValidationError(fmt(key) + ' must be a float.');
throw new ValidationError(key, 'float');
value = parseFloat(value);
if (!isFinite(value))
throw new ValidationError(fmt(key) + ' must be a float.');
throw new ValidationError(key, 'float');
return value;
};
@ -203,7 +203,7 @@ Validator.prototype.u32 = function u32(key, fallback) {
return fallback;
if ((value >>> 0) !== value)
throw new ValidationError(fmt(key) + ' must be a uint32.');
throw new ValidationError(key, 'uint32');
return value;
};
@ -225,7 +225,7 @@ Validator.prototype.u64 = function u64(key, fallback) {
return fallback;
if (value % 1 !== 0 || value < 0 || value > 0x1fffffffffffff)
throw new ValidationError(fmt(key) + ' must be a uint64.');
throw new ValidationError(key, 'uint64');
return value;
};
@ -247,7 +247,7 @@ Validator.prototype.i32 = function i32(key, fallback) {
return fallback;
if ((value | 0) !== value)
throw new ValidationError(fmt(key) + ' must be an int32.');
throw new ValidationError(key, 'int32');
return value;
};
@ -269,7 +269,7 @@ Validator.prototype.i64 = function i64(key, fallback) {
return fallback;
if (value % 1 !== 0 || Math.abs(value) > 0x1fffffffffffff)
throw new ValidationError(fmt(key) + ' must be an int64.');
throw new ValidationError(key, 'int64');
return value;
};
@ -292,22 +292,22 @@ Validator.prototype.amt = function amt(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'number')
throw new ValidationError(fmt(key) + ' must be an amount.');
throw new ValidationError(key, 'amount');
return value;
}
if (!/^\d+(\.\d{0,8})?$/.test(value))
throw new ValidationError(fmt(key) + ' must be an amount.');
throw new ValidationError(key, 'amount');
value = parseFloat(value);
if (!isFinite(value))
throw new ValidationError(fmt(key) + ' must be an amount.');
throw new ValidationError(key, 'amount');
value *= 1e8;
if (value % 1 !== 0 || value < 0 || value > 0x1fffffffffffff)
throw new ValidationError(fmt(key) + ' must be an amount (uint64).');
throw new ValidationError(key, 'amount (uint64)');
return value;
};
@ -331,7 +331,7 @@ Validator.prototype.btc = function btc(key, fallback) {
value *= 1e8;
if (value % 1 !== 0 || value < 0 || value > 0x1fffffffffffff)
throw new ValidationError(fmt(key) + ' must be a btc float (uint64).');
throw new ValidationError(key, 'btc float (uint64)');
return value;
};
@ -355,19 +355,19 @@ Validator.prototype.hash = function hash(key, fallback) {
if (typeof value !== 'string') {
if (!Buffer.isBuffer(value))
throw new ValidationError(fmt(key) + ' must be a hash.');
throw new ValidationError(key, 'hash');
if (value.length !== 32)
throw new ValidationError(fmt(key) + ' must be a hash.');
throw new ValidationError(key, 'hash');
return value.toString('hex');
}
if (value.length !== 64)
throw new ValidationError(fmt(key) + ' must be a hex string.');
throw new ValidationError(key, 'hex string');
if (!/^[0-9a-f]+$/i.test(value))
throw new ValidationError(fmt(key) + ' must be a hex string.');
throw new ValidationError(key, 'hex string');
for (let i = 0; i < value.length; i += 2)
out = value.slice(i, i + 2) + out;
@ -413,7 +413,7 @@ Validator.prototype.numstr = function numstr(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'number')
throw new ValidationError(fmt(key) + ' must be a number or string.');
throw new ValidationError(key, 'number or string');
return value;
}
@ -451,7 +451,7 @@ Validator.prototype.bool = function bool(key, fallback) {
if (typeof value !== 'string') {
if (typeof value !== 'boolean')
throw new ValidationError(fmt(key) + ' must be a boolean.');
throw new ValidationError(key, 'boolean');
return value;
}
@ -461,7 +461,7 @@ Validator.prototype.bool = function bool(key, fallback) {
if (value === 'false' || value === '0')
return false;
throw new ValidationError(fmt(key) + ' must be a boolean.');
throw new ValidationError(key, 'boolean');
};
/**
@ -487,14 +487,14 @@ Validator.prototype.buf = function buf(key, fallback, enc) {
if (typeof value !== 'string') {
if (!Buffer.isBuffer(value))
throw new ValidationError(fmt(key) + ' must be a buffer.');
throw new ValidationError(key, 'buffer');
return value;
}
data = Buffer.from(value, enc);
if (data.length !== Buffer.byteLength(value, enc))
throw new ValidationError(fmt(key) + ' must be a ' + enc + ' string.');
throw new ValidationError(key, `${enc} string`);
return data;
};
@ -518,7 +518,7 @@ Validator.prototype.array = function array(key, fallback) {
if (typeof value !== 'string') {
if (!Array.isArray(value))
throw new ValidationError(fmt(key) + ' must be a list/array.');
throw new ValidationError(key, 'list/array');
return value;
}
@ -552,7 +552,7 @@ Validator.prototype.obj = function obj(key, fallback) {
return fallback;
if (!value || typeof value !== 'object')
throw new ValidationError(fmt(key) + ' must be an object.');
throw new ValidationError(key, 'object');
return value;
};
@ -574,7 +574,7 @@ Validator.prototype.func = function func(key, fallback) {
return fallback;
if (typeof value !== 'function')
throw new ValidationError(fmt(key) + ' must be a function.');
throw new ValidationError(key, 'function');
return value;
};
@ -598,14 +598,14 @@ function inherits(child, parent) {
});
}
function ValidationError(msg) {
function ValidationError(key, type) {
Error.call(this);
if (Error.captureStackTrace)
Error.captureStackTrace(this, ValidationError);
this.type = 'ValidationError';
this.message = msg;
this.message = `${fmt(key)} must be a ${type}.`
}
inherits(ValidationError, Error);

View File

@ -454,7 +454,7 @@ Account.prototype.createKey = async function createKey(branch) {
this.nested = key;
break;
default:
throw new Error('Bad branch: ' + branch);
throw new Error(`Bad branch: ${branch}.`);
}
this.save();

View File

@ -267,7 +267,7 @@ MasterKey.prototype.derive = async function derive(passwd) {
case MasterKey.alg.SCRYPT:
return await scrypt.deriveAsync(passwd, salt, N, r, p, 32);
default:
throw new Error('Unknown algorithm: ' + this.alg);
throw new Error(`Unknown algorithm: ${this.alg}.`);
}
};

View File

@ -60,7 +60,7 @@ jobs._execute = function execute(p) {
case packets.types.SCRYPT:
return jobs.scrypt(p.passwd, p.salt, p.N, p.r, p.p, p.len);
default:
throw new Error('Unknown command: "' + p.cmd + '".');
throw new Error(`Unknown command: "${p.cmd}".`);
}
};

View File

@ -658,7 +658,7 @@ Worker.prototype.handlePacket = function handlePacket(packet) {
this.emit('event', packet.items);
break;
case packets.types.LOG:
this.emit('log', 'Worker ' + this.id);
this.emit('log', `Worker ${this.id}.`);
this.emit('log', packet.text);
break;
case packets.types.ERROR:
@ -771,7 +771,7 @@ Worker.prototype.resolveJob = function resolveJob(id, result) {
let job = this.pending.get(id);
if (!job)
throw new Error('Job ' + id + ' is not in progress.');
throw new Error(`Job ${id} is not in progress.`);
job.resolve(result);
};
@ -786,7 +786,7 @@ Worker.prototype.rejectJob = function rejectJob(id, err) {
let job = this.pending.get(id);
if (!job)
throw new Error('Job ' + id + ' is not in progress.');
throw new Error(`Job ${id} is not in progress.`);
job.reject(err);
};