From 83f1e98a8e9ae997c7c4d957fc7c57d30ec67c61 Mon Sep 17 00:00:00 2001 From: Yash Ladha Date: Sun, 5 Apr 2020 15:05:52 +0530 Subject: [PATCH] lib: created isValidCallback helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit check for callback function is moved to a separate function. This piece of code is being shared by other entities as well. PR-URL: https://github.com/nodejs/node/pull/32665 Reviewed-By: Zeyu Yang Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Gerhard Stöbich --- lib/internal/validators.js | 9 ++++++++- lib/timers.js | 14 ++++---------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/lib/internal/validators.js b/lib/internal/validators.js index 04c05c2851548a..54f19215296c87 100644 --- a/lib/internal/validators.js +++ b/lib/internal/validators.js @@ -14,7 +14,8 @@ const { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, - ERR_UNKNOWN_SIGNAL + ERR_UNKNOWN_SIGNAL, + ERR_INVALID_CALLBACK, } } = require('internal/errors'); const { normalizeEncoding } = require('internal/util'); @@ -194,6 +195,11 @@ function validatePort(port, name = 'Port', { allowZero = true } = {}) { return port | 0; } +const validateCallback = hideStackFrames((callback) => { + if (typeof callback !== 'function') + throw new ERR_INVALID_CALLBACK(callback); +}); + module.exports = { isInt32, isUint32, @@ -210,4 +216,5 @@ module.exports = { validateSignalName, validateString, validateUint32, + validateCallback, }; diff --git a/lib/timers.js b/lib/timers.js index 5904ec9bd3b533..324752506c7a86 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -53,8 +53,8 @@ const { promisify: { custom: customPromisify }, deprecate } = require('internal/util'); -const { ERR_INVALID_CALLBACK } = require('internal/errors').codes; const debug = require('internal/util/debuglog').debuglog('timer'); +const { validateCallback } = require('internal/validators'); const { destroyHooksExist, @@ -118,9 +118,7 @@ function enroll(item, msecs) { function setTimeout(callback, after, arg1, arg2, arg3) { - if (typeof callback !== 'function') { - throw new ERR_INVALID_CALLBACK(callback); - } + validateCallback(callback); let i, args; switch (arguments.length) { @@ -165,9 +163,7 @@ function clearTimeout(timer) { } function setInterval(callback, repeat, arg1, arg2, arg3) { - if (typeof callback !== 'function') { - throw new ERR_INVALID_CALLBACK(callback); - } + validateCallback(callback); let i, args; switch (arguments.length) { @@ -249,9 +245,7 @@ const Immediate = class Immediate { }; function setImmediate(callback, arg1, arg2, arg3) { - if (typeof callback !== 'function') { - throw new ERR_INVALID_CALLBACK(callback); - } + validateCallback(callback); let i, args; switch (arguments.length) {