Example how to write good function with validation
From node.js source code, like: https://github.com/nodejs/node/blob/f8aff90235d5cdc9b2a4472107edbec645735dcc/lib/internal/process/per_thread.js#L282 Function for validation throw error when variable type is not valid, like validateString() or validateArray().
function execve(execPath, args, env) {
emitExperimentalWarning('process.execve');
const { isMainThread } = require('internal/worker');
if (!isMainThread) {
throw new ERR_WORKER_UNSUPPORTED_OPERATION('Calling process.execve');
} else if (process.platform === 'win32') {
throw new ERR_FEATURE_UNAVAILABLE_ON_PLATFORM('process.execve');
}
validateString(execPath, 'execPath');
validateArray(args, 'args');
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (typeof arg !== 'string' || StringPrototypeIncludes(arg, '\u0000')) {
throw new ERR_INVALID_ARG_VALUE(`args[${i}]`, arg, 'must be a string without null bytes');
}
}
const envArray = [];
if (env !== undefined) {
validateObject(env, 'env');
for (const { 0: key, 1: value } of ObjectEntries(env)) {
if (
typeof key !== 'string' ||
typeof value !== 'string' ||
StringPrototypeIncludes(key, '\u0000') ||
StringPrototypeIncludes(value, '\u0000')
) {
throw new ERR_INVALID_ARG_VALUE(
'env', env, 'must be an object with string keys and values without null bytes',
);
} else {
ArrayPrototypePush(envArray, `${key}=${value}`);
}
}
}
if (execveDiagnosticChannel.hasSubscribers) {
execveDiagnosticChannel.publish({ execPath, args, env: envArray });
}
// Perform the system call
_execve(execPath, args, envArray);
}