UNPKG

verror-0

Version:

VError without dependencies on top of nodejs standart library

61 lines (60 loc) 2.17 kB
import { format } from 'node:util'; import { isError } from './is-error.js'; export function parseArgs(args) { let argv; if (typeof args !== 'object' || args === null || !('argv' in args)) { throw new Error('args should be object'); } if (!Array.isArray(args.argv)) { throw new Error('argv should be array'); } argv = args.argv; const options = {}; let sprintfArgs = []; // Определим какая форма вызова используется. if (argv.length === 0) { // Тут ничего делать не нужно. } else if (isError(argv[0])) { options.cause = argv[0]; // Слайсим все элементы как аргументы sprintf после причины/ошибки. sprintfArgs = argv.slice(1); } else if (typeof argv[0] === 'object' && argv[0] !== null) { for (const k in argv[0]) { options[k] = argv[0][k]; } sprintfArgs = argv.slice(1); } else { if (typeof argv[0] !== 'string') { throw new Error('first argument to VError or WError constructor must be a string, object, or Error'); } // В случае когда передана строка - все аргументы идут для sprintf. sprintfArgs = argv; } let shortmessage; if (sprintfArgs.length === 0) { shortmessage = ''; } else { // 1й - message, остальные - параметры. shortmessage = format(...sprintfArgs); } if (args.strict) { options.strict = true; } if (options.strict) { if (sprintfArgs.some((v) => v === null || v === undefined)) { throw new Error('strict mode violation: one or more arguments in sprintf args are null or undefined'); } } if ('maxCauseDepth' in options && (typeof options.maxCauseDepth !== 'number' || options.maxCauseDepth <= 0)) { throw new Error('maxCauseDepth must be a positive number'); } options.maxCauseDepth = options.maxCauseDepth ?? 3; return { options, shortmessage }; }