validation.js
This file
Path
lib/ipc/validation.js
46 lines · 2.1 KiB · JavaScript
Last changed by
Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
History of this fileTake it
Add promise-based IPC (#1059)ehmickybefore adoptionacc2b68
lines 1–46why, one step back1// Better error message when forgetting to set `ipc: true` and using the IPC methods2export const validateIpcOption = (methodName, isSubprocess, ipc) => {3 if (!ipc) {4 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() can only be used if the \`ipc\` option is \`true\`.`);5 }6};78// Better error message when one process does not send/receive messages once the other process has disconnected9export const validateConnection = (methodName, isSubprocess, isConnected) => {10 if (!isConnected) {11 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);12 }13};1415const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';1617const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';1819// Better error message when sending messages which cannot be serialized.20// Works with both `serialization: 'advanced'` and `serialization: 'json'`.21export const handleSerializationError = (error, isSubprocess, message) => {22 if (isSerializationError(error)) {23 error.message = `${getNamespaceName(isSubprocess)}sendMessage()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;24 }25};2627const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)28 || SERIALIZATION_ERROR_MESSAGES.some(serializationErrorMessage => message.includes(serializationErrorMessage));2930// `error.code` set by Node.js when it failed to serialize the message31const SERIALIZATION_ERROR_CODES = new Set([32 // Message is `undefined`33 'ERR_MISSING_ARGS',34 // Message is a function, a bigint, a symbol35 'ERR_INVALID_ARG_TYPE',36]);3738// `error.message` set by Node.js when it failed to serialize the message39const SERIALIZATION_ERROR_MESSAGES = [40 // Message is a promise or a proxy, with `serialization: 'advanced'`41 'could not be cloned',42 // Message has cycles, with `serialization: 'json'`43 'circular structure',44 // Message has cycles inside toJSON(), with `serialization: 'json'`45 'call stack size exceeded',46];