Ошибка unhandled error что это

На чтение 6 мин. Просмотров 13.1k. Опубликовано 03.09.2019

Содержание

  1. 6 решений для исправления необработанных исключительных ошибок
  2. Действия по исправлению ошибок необработанных исключений в Windows 10
  3. Решение 1. Выполните чистую загрузку
  4. Решение 2. Выполните сканирование SFC
  5. Решение 3. Запустите средство устранения неполадок оборудования
  6. Решение 4. Выполните проверку на вирусы
  7. Решение 5. Удалите и переустановите .NET Framework
  8. Решение 6. Запустите средство очистки .NET Framework.

6 решений для исправления необработанных исключительных ошибок

  1. Выполнить чистую загрузку
  2. Выполнить сканирование SFC
  3. Запустите средство устранения неполадок оборудования .
  4. Выполнить проверку на вирусы
  5. Удаление и повторная установка .NET Framework
  6. Запустите инструмент очистки .NET Framework

Исключения можно рассматривать как известную форму ошибки, с которой операционная система запрограммирована для устранения. Другими словами, ОС – в данном случае Windows – знает об этой проблеме и уже знает, как с ней справиться.

К сожалению, также может быть какое-то исключение, которое выходит за рамки Windows. Именно эти сценарии стали известны как ошибки необработанных исключений . Это потому, что Windows не знает, как обрабатывать исключения. Тем не менее, эти ошибки также могут быть легко исправлены, хотя единственный улов здесь заключается в том, что может потребоваться некоторое время, прежде чем вы вернетесь в нужное русло.

Действия по исправлению ошибок необработанных исключений в Windows 10

Решение 1. Выполните чистую загрузку

Это позволит компьютеру запускать только минимальный набор драйверов и программ. Таким образом, вы будете знать, какая сторонняя программа, если таковая имеется, приводит к ошибке. Вот как это делается.

  • Запустите msconfig. Это можно сделать, просто набрав msconfig в окне поиска Cortana и выберите Конфигурация системы в результаты поиска показаны. Либо нажмите клавишу Windows + R , чтобы запустить Выполнить , введите msconfig и нажмите ОК .

Ваш компьютер теперь будет загружаться в так называемой среде чистой загрузки, где все сторонние программы отключены. По этой причине ПК может не иметь всех функциональных возможностей, хотя, к сожалению, нет, они будут восстановлены на следующем этапе.

  • СВЯЗАННЫЕ: Полное исправление: ошибка ОСНОВНОГО РЕЖИМА КЕРНЕЛА НЕ ОБРАБОТАНА в Windows 10

Между тем, вот как узнать, какая программа может играть в шалости.

  • Запустите msconfig еще раз, выполнив шаги, упомянутые выше.
  • В диалоговом окне Конфигурация системы выберите Службы .
  • Затем установите флажок Скрыть все службы Microsoft .
  • Выберите, чтобы включить половину из автозагрузки программ в Службах .
  • Нажмите ОК , а затем Перезагрузите .
  • Если проблема не возникает, все выбранные вами программы прошли тестирование.
  • Повторите процесс со следующей половиной.
  • Если проблема возникает, запустите msconfig > Службы .
  • Выберите половину из программ, которые вы выбрали во время первого запуска, и Перезапустите .
  • Повторите этот процесс с половиной программ каждый раз, пока не найдете проблемную программу.

Как только вы нашли программу, вызывающую ошибку, посмотрите, есть ли обновленная версия для этой же версии. Или удалите переустановку так же, чтобы увидеть, если проблема решена. Вы также можете связаться с производителем, чтобы узнать, могут ли они помочь решить проблему.

  • СВЯЗАННО: ИСКЛЮЧЕНИЕ ПРЕРЫВАНИЯ ПОЛНОЙ ФИКСИРОВКИ НЕ РАБОТАЕТ в Windows 10

Решение 2. Выполните сканирование SFC

Эта операция выполняет сканирование всех системных файлов и вносит необходимые изменения по мере необходимости. Это делает его чрезвычайно пригодным для работы с ошибками необработанных исключений. Вот как выполнить sfc scan .

  • Запустите командную строку , введя cmd в поле поиска Cortana .В показанном результате поиска щелкните правой кнопкой мыши Командная строка и выберите Запуск от имени администратора . Кроме того, вы также можете открыть окно Выполнить , удерживая клавишу Windows + R , введите cmd и нажмите Enter.
  • В окне командной строки введите sfc/scannow и нажмите Enter .
  • Для завершения сканирования может потребоваться несколько секунд. Терпеливо ждать, пока его показы 100% сканирования завершены.

Решение 3. Запустите средство устранения неполадок оборудования

Любые проблемы с оборудованием также могут быть причиной появления ошибки. Это делает крайне необходимым выполнять сканирование оборудования и устройств, чтобы исключить вероятность того, что аппаратное обеспечение или устройство где-то сыграют свою роль.

  • Чтобы определить такое оборудование, введите следующую команду в окнах Выполнить и нажмите Enter или нажмите кнопку ОК : % systemroot% system32 msdt.exe -id DeviceDiagnostic
  • Следуйте инструкциям на экране, чтобы определить, есть ли какое-либо оборудование.
  • Откройте диалоговое окно Выполнить , используя шаги, упомянутые в предыдущем разделе.

Вы также можете запустить средство устранения неполадок оборудования на странице настроек, как показано на снимке экрана ниже.

  • СВЯЗАННЫЕ: полное исправление: «Исключение режима ядра не обработано M» в Windows 10

Решение 4. Выполните проверку на вирусы

Есть также вероятность того, что вирусная атака является причиной таких ошибок. Поэтому настоятельно рекомендуется выполнить полное и тщательное сканирование вашей системы, чтобы убедиться, что на вашем компьютере нет вирусов, или справиться с ситуацией, когда на вашем компьютере есть вирусная атака.

Также убедитесь, что ваши файлы определений вирусов обновлены и ваш компьютер постоянно защищен. Откройте Центр безопасности Защитника Windows , чтобы выполнить аудит безопасности вашего компьютера. Нажмите на маленький значок стрелки в левом нижнем углу панели задач, чтобы открыть Центр безопасности Защитника Windows . Или вы также можете ввести то же самое в поле поиска Cortana .

Кроме того, лучше всего позволить защитнику Microsoft выполнять эту работу, а не какое-либо стороннее антивирусное программное обеспечение.

Решение 5. Удалите и переустановите .NET Framework

Это также еще один способ справиться с необработанной ошибкой исключения. Вот шаги:

  • Запустите Панель управления , нажав Пуск > Система Windows > Панель управления . Кроме того, вы можете просто ввести Панель управления в окне поиска Cortana и выбрать из отображаемых результатов поиска.
  • Выберите Программы > Программы и функции . Найдите Microsoft .NET Framework .
  • Нажмите правой кнопкой мыши и выберите Удалить .
  • После завершения удаления установите обновление Windows .
  • Для этого перейдите в раздел Пуск > Настройки > Обновление и безопасность .

.NET Framework будет установлен автоматически. Кроме того, вы также можете загрузить его вручную с официального сайта Microsoft – dotnet.microsoft.com .

Решение 6. Запустите средство очистки .NET Framework.

Также рекомендуется убедиться, что у вас нет проблем с .NET Framework , установленным на вашем ПК. У вас будет вся информация и процедуры, перечисленные здесь для запуска инструмента.

Между тем, вот несколько других ресурсов, которые могут вас заинтересовать:

  • Исправлено: SYSTEM_SERVICE_EXCEPTION ошибка в Windows 10
  • Исправлено: ошибка MACHINE_CHECK_EXCEPTION в Windows 10
  • Исправлено: SYSTEM_SERVICE_EXCEPTION ошибка в Windows 10

Ошибки¶

Приложения, работающие на Node.js, обычно сталкиваются с четырьмя категориями ошибок:

  • Стандартные ошибки JavaScript, такие как {EvalError}, {SyntaxError}, {RangeError}, {ReferenceError}, {TypeError} и {URIError}.
  • Системные ошибки, вызванные ограничениями базовой операционной системы, например, попытка открыть несуществующий файл или попытка отправить данные через закрытый сокет.
  • Пользовательские ошибки, вызванные кодом приложения.
  • AssertionError — это специальный класс ошибок, которые могут быть вызваны, когда Node.js обнаруживает исключительное нарушение логики, которое никогда не должно происходить. Обычно их вызывает модуль node:assert.

Все JavaScript и системные ошибки, вызываемые Node.js, наследуются от или являются экземплярами стандартного класса JavaScript {Error} и гарантированно предоставляют по крайней мере свойства, доступные для этого класса.

Распространение и перехват ошибок¶

Node.js поддерживает несколько механизмов для распространения и обработки ошибок, возникающих во время работы приложения. То, как эти ошибки сообщаются и обрабатываются, полностью зависит от типа Error и стиля вызываемого API.

Все ошибки JavaScript обрабатываются как исключения, которые немедленно генерируют и выбрасывают ошибку, используя стандартный механизм JavaScript throw. Они обрабатываются с помощью конструкции try...catch, предоставляемой языком JavaScript.

// Выброс с ошибкой ReferenceError, потому что z не определен.
try {
    const m = 1;
    const n = m + z;
} catch (err) {
    // Обрабатываем ошибку здесь.
}

Любое использование механизма JavaScript throw вызовет исключение, которое должно быть обработано с помощью try...catch, иначе процесс Node.js немедленно завершится.

За редким исключением, синхронные API (любой блокирующий метод, который не принимает функцию callback, например, fs.readFileSync), будут использовать throw для сообщения об ошибках.

Ошибки, возникающие в асинхронных API, могут сообщаться различными способами:

  • Большинство асинхронных методов, которые принимают функцию callback, принимают объект Error, передаваемый в качестве первого аргумента этой функции. Если первый аргумент не является null и представляет собой экземпляр Error, то произошла ошибка, которую следует обработать.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    const fs = require('node:fs');
    fs.readFile(
        'файл, который не существует',
        (err, data) => {
            if (err) {
                console.error(
                    'Произошла ошибка при чтении файла!',
                    err
                );
                return;
            }
            // Иначе обрабатываем данные
        }
    );
    
  • Когда асинхронный метод вызывается на объекте, который является EventEmitter, ошибки могут быть направлены в событие 'error' этого объекта.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    const net = require('node:net');
    const connection = net.connect('localhost');
    
    // Добавление обработчика события 'error' к потоку:
    connection.on('error', (err) => {
        // Если соединение сбрасывается сервером, или если не удается
        // соединиться вообще, или при любой ошибке, с которой столкнулось
        // соединением, ошибка будет отправлена сюда.
        console.error(err);
    });
    
    connection.pipe(process.stdout);
    
  • Несколько типично асинхронных методов в API Node.js все еще могут использовать механизм throw для создания исключений, которые должны обрабатываться с помощью try...catch. Полного списка таких методов нет; пожалуйста, обратитесь к документации каждого метода для определения требуемого механизма обработки ошибок.

Использование механизма событий error наиболее характерно для API stream-based и event emitter-based, которые сами по себе представляют серию асинхронных операций во времени (в отличие от одной операции, которая может пройти или не пройти).

const EventEmitter = require('node:events');
const ee = new EventEmitter();

setImmediate(() => {
    // This will crash the process because no 'error' event
    // handler has been added.
    ee.emit('error', new Error('This will crash'));
});

Ошибки, сгенерированные таким образом, не могут быть перехвачены с помощью try...catch, поскольку они возникают после того, как вызывающий код уже завершился.

Разработчики должны обратиться к документации для каждого метода, чтобы определить, как именно распространяются ошибки, вызванные этими методами.

Обратные вызовы по ошибке¶

Большинство асинхронных методов, представленных в API ядра Node.js, следуют идиоматическому шаблону, называемому первым обратным вызовом при ошибке. В этом шаблоне функция обратного вызова передается методу в качестве аргумента. Когда операция либо завершается, либо возникает ошибка, вызывается функция обратного вызова с объектом Error (если таковой имеется), переданным в качестве первого аргумента. Если ошибка не была обнаружена, первый аргумент будет передан как null.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
const fs = require('node:fs');

function errorFirstCallback(err, data) {
    if (err) {
        console.error('Произошла ошибка', err);
        return;
    }
    console.log(data);
}

fs.readFile(
    '/some/file/that/does-not-exist',
    errorFirstCallback
);
fs.readFile(
    '/some/file/that/does-exist',
    errorFirstCallback
);

Механизм JavaScript try...catch нельзя использовать для перехвата ошибок, генерируемых асинхронными API. Частой ошибкой новичков является попытка использовать throw внутри обратного вызова error-first:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// THIS WILL NOT WORK:
const fs = require('node:fs');

try {
    fs.readFile(
        '/some/file/that/does-not-exist',
        (err, data) => {
            // Mistaken assumption: throwing here...
            if (err) {
                throw err;
            }
        }
    );
} catch (err) {
    // This will not catch the throw!
    console.error(err);
}

Это не сработает, потому что функция обратного вызова, переданная в fs.readFile(), вызывается асинхронно. К тому моменту, когда callback будет вызван, окружающий код, включая блок try...catch, уже завершится. Выброс ошибки внутри обратного вызова может привести к краху процесса Node.js в большинстве случаев. Если включены domains, или обработчик был зарегистрирован в process.on('uncaughtException'), такие ошибки могут быть перехвачены.

Класс: Error

Общий объект JavaScript {Error}, который не обозначает никаких конкретных обстоятельств того, почему произошла ошибка. Объекты Error фиксируют «трассировку стека», детализирующую точку в коде, в которой Error был инстанцирован, и могут предоставлять текстовое описание ошибки.

Все ошибки, генерируемые Node.js, включая все системные ошибки и ошибки JavaScript, будут либо экземплярами класса Error, либо наследоваться от него.

### new Error(message[, options])

  • сообщение {строка}
  • options {Object}
    • cause {any} Ошибка, которая вызвала вновь созданную ошибку.

Создает новый объект Error и устанавливает свойство error.message в предоставленное текстовое сообщение. Если в качестве message передан объект, текстовое сообщение генерируется вызовом String(message). Если передана опция cause, она присваивается свойству error.cause. Свойство error.stack будет представлять точку в коде, в которой была вызвана new Error(). Трассировка стека зависит от V8’s stack trace API. Трассировка стека распространяется только на (a) начало синхронного выполнения кода, или (b) количество кадров, заданное свойством Error.stackTraceLimit, в зависимости от того, что меньше.

Error.captureStackTrace(targetObject[, constructorOpt])

  • targetObject {Object}
  • constructorOpt {Функция}

Создает свойство .stack на targetObject, которое при обращении к нему возвращает строку, представляющую место в коде, в котором была вызвана Error.captureStackTrace().

const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Аналогично `new Error().stack`.

Первая строка трассировки будет иметь префикс ${myObject.name}: ${myObject.message}.

Необязательный аргумент constructorOpt принимает функцию. Если он задан, все фреймы выше constructorOpt, включая constructorOpt, будут опущены в сгенерированной трассировке стека.

Аргумент constructorOpt полезен для сокрытия от пользователя деталей реализации генерации ошибок. Например:

function MyError() {
    Error.captureStackTrace(this, MyError);
}

// Без передачи MyError в captureStackTrace, MyError
// кадр будет отображаться в свойстве .stack. Передавая
// конструктору, мы опускаем этот кадр и сохраняем все кадры ниже него.
new MyError().stack;

Error.stackTraceLimit

  • {число}

Свойство Error.stackTraceLimit определяет количество кадров стека, собираемых трассировкой стека (независимо от того, генерируется ли она new Error().stack или Error.captureStackTrace(obj)).

Значение по умолчанию — 10, но может быть установлено в любое допустимое число JavaScript. Изменения будут влиять на любую трассировку стека, захваченную после изменения значения.

Если значение не равно числу или равно отрицательному числу, трассировка стека не будет фиксироваться.

error.cause

  • {любая}

Если присутствует, свойство error.cause является основной причиной Error. Оно используется, когда вы ловите ошибку и бросаете новую с другим сообщением или кодом, чтобы сохранить доступ к исходной ошибке.

Свойство error.cause обычно устанавливается вызовом new Error(message, { cause }). Оно не устанавливается конструктором, если не указан параметр cause.

Это свойство позволяет связывать ошибки в цепочку. При сериализации объектов Error, util.inspect() рекурсивно сериализует error.cause, если оно установлено.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const cause = new Error(
    'The remote HTTP server responded with a 500 status'
);
const symptom = new Error('The message failed to send', {
    cause,
});

console.log(symptom);
// Prints:
//   Error: The message failed to send
//       at REPL2:1:17
//       at Script.runInThisContext (node:vm:130:12)
//       ... 7 lines matching cause stack trace ...
//       at [_line] [as _line] (node:internal/readline/interface:886:18) {
//     [cause]: Error: The remote HTTP server responded with a 500 status
//         at REPL1:1:15
//         at Script.runInThisContext (node:vm:130:12)
//         at REPLServer.defaultEval (node:repl:574:29)
//         at bound (node:domain:426:15)
//         at REPLServer.runBound [as eval] (node:domain:437:12)
//         at REPLServer.onLine (node:repl:902:10)
//         at REPLServer.emit (node:events:549:35)
//         at REPLServer.emit (node:domain:482:12)
//         at [_onLine] [as _onLine] (node:internal/readline/interface:425:12)
//         at [_line] [as _line] (node:internal/readline/interface:886:18)

error.code

  • {string}

Свойство error.code — это строковая метка, которая идентифицирует вид ошибки. error.code является наиболее стабильным способом идентификации ошибки. Он будет меняться только между основными версиями Node.js. В отличие от этого, строки error.message могут изменяться между любыми версиями Node.js. Подробности о конкретных кодах см. в Node.js error codes.

error.message

  • {string}

Свойство error.message — это строковое описание ошибки, заданное вызовом new Error(message). Переданное конструктору message также появится в первой строке трассировки стека Error, однако изменение этого свойства после создания объекта Error может не изменить первую строку трассировки стека (например, если error.stack будет прочитан до изменения этого свойства).

const err = new Error('Сообщение');
console.error(err.message);
// Выводит: Сообщение

error.stack

  • {строка}

Свойство error.stack представляет собой строку, описывающую точку в коде, в которой Error была инстанцирована.

Error: Things keep happening!
   at /home/gbusey/file.js:525:2
   at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
   at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
   at increaseSynergy (/home/gbusey/actors.js:701:6)

Первая строка отформатирована как <имя класса ошибки>: <сообщение об ошибке>, а за ней следует серия стековых кадров (каждая строка начинается с «at»). Каждый кадр описывает место вызова в коде, которое привело к возникновению ошибки. V8 пытается отобразить имя для каждой функции (по имени переменной, имени функции или имени метода объекта), но иногда ему не удается найти подходящее имя. Если V8 не может определить имя функции, для этого кадра будет отображаться только информация о местоположении. В противном случае будет выведено определенное имя функции с информацией о местоположении, заключенной в круглые скобки.

Фреймы генерируются только для функций JavaScript. Если, например, выполнение синхронно проходит через функцию аддона C++ под названием cheetahify, которая сама вызывает функцию JavaScript, фрейм, представляющий вызов cheetahify, не будет присутствовать в стековых трассах:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const cheetahify = require('./native-binding.node');

function makeFaster() {
    // `cheetahify()` *synchronously* calls speedy.
    cheetahify(function speedy() {
        throw new Error('oh no!');
    });
}

makeFaster();
// will throw:
//   /home/gbusey/file.js:6
//       throw new Error('oh no!');
//           ^
//   Error: oh no!
//       at speedy (/home/gbusey/file.js:6:11)
//       at makeFaster (/home/gbusey/file.js:5:3)
//       at Object.<anonymous> (/home/gbusey/file.js:10:1)
//       at Module._compile (module.js:456:26)
//       at Object.Module._extensions..js (module.js:474:10)
//       at Module.load (module.js:356:32)
//       at Function.Module._load (module.js:312:12)
//       at Function.Module.runMain (module.js:497:10)
//       at startup (node.js:119:16)
//       at node.js:906:3

Информация о местоположении будет одной из:

  • native, если кадр представляет собой вызов внутри V8 (как в [].forEach).
  • plain-filename.js:line:column, если фрейм представляет собой вызов внутри Node.js.
  • /absolute/path/to/file.js:line:column, если фрейм представляет собой вызов в пользовательской программе (использующей систему модулей CommonJS), или ее зависимостях.
  • <transport-protocol>:///url/to/module/file.mjs:line:column, если кадр представляет собой вызов в пользовательской программе (с использованием системы модулей ES), или ее зависимостей.

Строка, представляющая трассировку стека, лениво генерируется при **обращении к свойству error.stack.

Количество кадров, захватываемых трассировкой стека, ограничено меньшим из значений Error.stackTraceLimit или количеством доступных кадров на текущем такте цикла событий.

Класс: AssertionError

  • Расширяет: {errors.Error}

Указывает на неудачу утверждения. Подробнее см. в Класс: assert.AssertionError.

Класс: RangeError

  • Расширяет: {errors.Error}

Указывает, что предоставленный аргумент не входит в набор или диапазон допустимых значений для функции; будь то числовой диапазон, или вне набора опций для данного параметра функции.

require('node:net').connect(-1);
// Выбрасывает "RangeError: параметр "port" должен быть >= 0 и < 65536: -1"

Node.js будет генерировать и бросать экземпляры RangeError немедленно в качестве формы проверки аргументов.

Класс: ReferenceError

  • Расширяет: {errors.Error}

Указывает на попытку доступа к переменной, которая не определена. Такие ошибки обычно указывают на опечатки в коде или на другие сбои в программе.

Хотя клиентский код может генерировать и распространять эти ошибки, на практике это делает только V8.

doesNotExist;
// Выбрасывает ошибку ReferenceError, doesNotExist не является переменной в этой программе.

Если только приложение не генерирует и не выполняет код динамически, случаи ReferenceError указывают на ошибку в коде или его зависимостях.

Класс: SyntaxError

  • Расширяет: {errors.Error}

Указывает, что программа не является валидным JavaScript. Эти ошибки могут генерироваться и распространяться только в результате оценки кода. Оценка кода может происходить в результате eval, Function, require или vm. Эти ошибки почти всегда свидетельствуют о неработающей программе.

try {
    require('node:vm').runInThisContext('binary ! isNotOk');
} catch (err) {
    // 'err' will be a SyntaxError.
}

Экземпляры SyntaxError не могут быть устранены в контексте, который их создал — они могут быть пойманы только другими контекстами.

Класс: SystemError

  • Расширяет: {errors.Error}

Node.js генерирует системные ошибки, когда в среде выполнения возникают исключения. Обычно они возникают, когда приложение нарушает ограничения операционной системы. Например, системная ошибка возникнет, если приложение попытается прочитать несуществующий файл.

  • address {строка} Если присутствует, адрес, с которым произошел сбой сетевого соединения.
  • code {string} Строковый код ошибки
  • dest {string} Если присутствует, назначение пути к файлу при сообщении об ошибке файловой системы
  • errno {number} Номер ошибки, предоставляемый системой
  • info {Object} Если присутствует, дополнительные сведения о состоянии ошибки
  • message {string} Предоставленное системой человекочитаемое описание ошибки
  • path {string} Если присутствует, путь к файлу при сообщении об ошибке файловой системы
  • port {number} Если присутствует, порт сетевого подключения, который недоступен
  • syscall {string} Имя системного вызова, вызвавшего ошибку

error.address

  • {строка}

Если присутствует, error.address — это строка, описывающая адрес, с которым не удалось установить сетевое соединение.

error.code

  • {строка}

Свойство error.code — это строка, представляющая код ошибки.

error.dest

  • {строка}

Если присутствует, то error.dest является местом назначения пути к файлу при сообщении об ошибке файловой системы.

error.errno

  • {number}

Свойство error.errno — это отрицательное число, которое соответствует коду ошибки, определенному в libuv Error handling.

В Windows номер ошибки, предоставляемый системой, будет нормализован libuv.

Чтобы получить строковое представление кода ошибки, используйте util.getSystemErrorName(error.errno).

error.info

  • {Object}

Если присутствует, error.info — это объект с подробной информацией о состоянии ошибки.

error.message

  • {string}

error.message — это предоставленное системой человекочитаемое описание ошибки.

error.path

  • {строка}

Если присутствует, error.path — это строка, содержащая соответствующее неверное имя пути.

error.port

  • {число}

Если присутствует, error.port — это порт сетевого подключения, который недоступен.

error.syscall

  • {строка}

Свойство error.syscall — это строка, описывающая syscall, который завершился неудачей.

Общие системные ошибки¶

Это список системных ошибок, часто встречающихся при написании программ на Node.js. Полный список см. на странице errno(3) man page.

  • EACCES (Разрешение отклонено): Была предпринята попытка получить доступ к файлу способом, запрещенным его разрешениями на доступ к файлу.

  • EADDRINUSE (Адрес уже используется): Попытка привязать сервер (net, http или https) к локальному адресу не удалась из-за того, что другой сервер в локальной системе уже занимает этот адрес.

  • ECONNREFUSED (Connection refused): Не удалось установить соединение, поскольку целевая машина активно отказывается от него. Обычно это происходит при попытке подключения к службе, которая неактивна на внешнем узле.

  • ECONNRESET (Connection reset by peer): Соединение было принудительно закрыто сверстником. Обычно это происходит в результате потери соединения на удаленном сокете из-за тайм-аута или перезагрузки. Часто встречается в модулях http и net.

  • EEXIST (Файл существует): Существующий файл был целью операции, которая требовала, чтобы цель не существовала.

  • EISDIR (Is a directory): Операция ожидала файл, но заданный путь оказался каталогом.

  • EMFILE (Слишком много открытых файлов в системе): Максимальное количество файловых дескрипторов, допустимое в системе, достигнуто, и запросы на другой дескриптор не могут быть выполнены, пока не будет закрыт хотя бы один. Это происходит при параллельном открытии большого количества файлов одновременно, особенно на системах (в частности, macOS), где существует низкий лимит файловых дескрипторов для процессов. Чтобы устранить низкий лимит, запустите ulimit -n 2048 в той же оболочке, в которой будет запущен процесс Node.js.

  • ENOENT (Нет такого файла или каталога): Обычно вызывается операциями fs, указывая на то, что компонент указанного пути не существует. По указанному пути не удалось найти ни одной сущности (файла или каталога).

  • ENOTDIR (Не каталог): Компонент указанного пути существует, но не является каталогом, как ожидалось. Обычно вызывается fs.readdir.

  • ENOTEMPTY (Каталог не пуст): Каталог с записями был целью операции, требующей пустого каталога, обычно fs.unlink.

  • ENOTFOUND (DNS-поиск не удался): Указывает на ошибку DNS либо EAI_NODATA, либо EAI_NONAME. Это не стандартная ошибка POSIX.

  • EPERM (Операция не разрешена): Была предпринята попытка выполнить операцию, требующую повышенных привилегий.

  • EPIPE (Сломанная труба): Запись в трубу, сокет или FIFO, для которой нет процесса для чтения данных. Обычно встречается на уровнях net и http, указывая на то, что удаленная сторона потока, на которую производится запись, была закрыта.

  • ETIMEDOUT (Операция завершилась): Запрос на подключение или отправку не прошел, потому что

Класс: TypeError

  • Расширяет {errors.Error}

Указывает, что предоставленный аргумент не является допустимым типом. Например, передача функции в параметр, который ожидает строку, будет TypeError.

require('node:url').parse(() => {});
// Выбросит TypeError, так как ожидается строка.

Node.js будет генерировать и бросать экземпляры TypeError немедленно в качестве формы проверки аргументов.

Исключения и ошибки¶

Исключение JavaScript — это значение, которое выбрасывается в результате некорректной операции или как цель оператора throw. Хотя не требуется, чтобы эти значения были экземплярами Error или классами, наследующими от Error, все исключения, выбрасываемые Node.js или временем выполнения JavaScript, будут экземплярами Error.

Некоторые исключения являются неустранимыми на уровне JavaScript. Такие исключения всегда приводят к аварийному завершению процесса Node.js. Примерами могут служить проверки assert() или вызовы abort() на уровне C++.

Ошибки OpenSSL¶

Ошибки, возникающие в crypto или tls, относятся к классу Error, и помимо стандартных свойств .code и .message могут иметь некоторые дополнительные свойства, специфичные для OpenSSL.

error.opensslErrorStack

Массив ошибок, который может дать представление о том, в каком месте библиотеки OpenSSL возникла ошибка.

error.function

Функция OpenSSL, в которой возникла ошибка.

error.library

Библиотека OpenSSL, в которой возникла ошибка.

error.reason

Человекочитаемая строка, описывающая причину ошибки.

Node.js error codes¶

ABORT_ERR

Используется, когда операция была прервана (обычно с помощью AbortController).

API, не использующие AbortSignal, обычно не выдают ошибку с этим кодом.

Этот код не использует обычное соглашение ERR_*, которое используется в ошибках Node.js, чтобы быть совместимым с AbortError веб-платформы.

ERR_ACCESS_DENIED

Специальный тип ошибки, возникающий всякий раз, когда Node.js пытается получить доступ к ресурсу, ограниченному Permission Model.

ERR_AMBIGUOUS_ARGUMENT

Аргумент функции используется таким образом, что подпись функции может быть неправильно понята. Модуль node:assert выбрасывает это сообщение, когда параметр message в assert.throws(block, message) совпадает с сообщением об ошибке, выброшенным block, поскольку такое использование предполагает, что пользователь считает message ожидаемым сообщением, а не сообщением, которое отобразит AssertionError, если block не выбросит сообщение.

ERR_ARG_NOT_ITERABLE

Аргумент iterable (т.е. значение, которое работает с циклами for...of) был необходим, но не предоставлялся API Node.js.

ERR_ASSERTION

Специальный тип ошибки, который может быть вызван всякий раз, когда Node.js обнаруживает исключительное нарушение логики, которое никогда не должно происходить. Обычно их вызывает модуль node:assert.

ERR_ASYNC_CALLBACK

Была предпринята попытка зарегистрировать что-то, что не является функцией, в качестве обратного вызова AsyncHooks.

ERR_ASYNC_TYPE

Тип асинхронного ресурса был неверным. Пользователи также могут определять свои собственные типы при использовании общедоступного API embedder.

ERR_BROTLI_COMPRESSION_FAILED

Данные, переданные в поток Brotli, не были успешно сжаты.

ERR_BROTLI_INVALID_PARAM

При построении потока Brotli был передан недопустимый ключ параметра.

ERR_BUFFER_CONTEXT_NOT_AVAILABLE

Была предпринята попытка создать экземпляр Node.js Buffer из кода аддона или embedder, находясь в JS-движке Context, который не связан с экземпляром Node.js. Данные, переданные в метод Buffer, будут освобождены к моменту возврата метода.

При возникновении этой ошибки возможной альтернативой созданию экземпляра Buffer является создание обычного Uint8Array, который отличается только прототипом получаемого объекта. Uint8Array общеприняты во всех основных API Node.js, где есть Buffer; они доступны во всех Contexts.

ERR_BUFFER_OUT_OF_BOUNDS

Была предпринята попытка выполнить операцию, выходящую за пределы Буфера.

ERR_BUFFER_TOO_LARGE

Была предпринята попытка создать Буфер большего размера, чем максимально допустимый.

ERR_CANNOT_WATCH_SIGINT

Node.js не смог проследить за сигналом SIGINT.

ERR_CHILD_CLOSED_BEFORE_REPLY

Дочерний процесс был закрыт до того, как родительский процесс получил ответ.

ERR_CHILD_PROCESS_IPC_REQUIRED

Используется, когда дочерний процесс форкируется без указания IPC-канала.

ERR_CHILD_PROCESS_STDIO_MAXBUFFER

Используется, когда основной процесс пытается прочитать данные из STDERR/STDOUT дочернего процесса, и длина данных превышает параметр maxBuffer.

ERR_CLOSED_MESSAGE_PORT

Была попытка использовать экземпляр MessagePort в закрытом состоянии, обычно после вызова .close().

ERR_CONSOLE_WRITABLE_STREAM

Console была создана без потока stdout, или Console имеет незаписываемый поток stdout или stderr.

ERR_CONSTRUCT_CALL_INVALID

Был вызван конструктор класса, который не является вызываемым.

ERR_CONSTRUCT_CALL_REQUIRED

Конструктор для класса был вызван без new.

ERR_CONTEXT_NOT_INITIALIZED

Контекст vm, переданный в API, еще не инициализирован. Это может произойти, если во время создания контекста произошла (и была поймана) ошибка, например, если при создании контекста произошел сбой выделения или был достигнут максимальный размер стека вызовов.

ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED

Был запрошен механизм клиентского сертификата, который не поддерживается используемой версией OpenSSL.

ERR_CRYPTO_ECDH_INVALID_FORMAT

В метод getPublicKey() класса crypto.ECDH() было передано недопустимое значение аргумента format.

ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY

В метод crypto.ECDH() класса computeSecret() было передано недопустимое значение аргумента key. Это означает, что открытый ключ лежит за пределами эллиптической кривой.

ERR_CRYPTO_ENGINE_UNKNOWN

В require('node:crypto').setEngine() был передан неверный идентификатор криптографического движка.

ERR_CRYPTO_FIPS_FORCED

Был использован аргумент командной строки --force-fips, но была попытка включить или отключить режим FIPS в модуле node:crypto.

ERR_CRYPTO_FIPS_UNAVAILABLE

Была предпринята попытка включить или отключить режим FIPS, но режим FIPS был недоступен.

ERR_CRYPTO_HASH_FINALIZED

hash.digest() был вызван несколько раз. Метод hash.digest() должен вызываться не более одного раза для каждого экземпляра объекта Hash.

ERR_CRYPTO_HASH_UPDATE_FAILED

hash.update() не удалось по какой-либо причине. Это должно происходить редко, если вообще происходит.

ERR_CRYPTO_INCOMPATIBLE_KEY

Данные криптографические ключи несовместимы с предпринимаемой операцией.

ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS

Выбранная кодировка открытого или закрытого ключа несовместима с другими вариантами.

ERR_CRYPTO_INITIALIZATION_FAILED

Инициализация криптоподсистемы не удалась.

ERR_CRYPTO_INVALID_AUTH_TAG

Был предоставлен недопустимый тег аутентификации.

ERR_CRYPTO_INVALID_COUNTER

Для шифра с режимом счетчика был предоставлен некорректный счетчик.

ERR_CRYPTO_INVALID_CURVE

Была предоставлена недопустимая эллиптическая кривая.

ERR_CRYPTO_INVALID_DIGEST

Был указан неверный алгоритм криптодайджеста.

ERR_CRYPTO_INVALID_IV

Был предоставлен недопустимый вектор инициализации.

ERR_CRYPTO_INVALID_JWK

Был предоставлен недопустимый веб-ключ JSON.

ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE

Тип данного объекта криптографического ключа не подходит для данной операции.

ERR_CRYPTO_INVALID_KEYLEN

Указана недопустимая длина ключа.

ERR_CRYPTO_INVALID_KEYPAIR

Была предоставлена недопустимая пара ключей.

ERR_CRYPTO_INVALID_KEYTYPE

Был предоставлен недопустимый тип ключа.

ERR_CRYPTO_INVALID_MESSAGELEN

Была предоставлена недопустимая длина сообщения.

ERR_CRYPTO_INVALID_SCRYPT_PARAMS

Были предоставлены неверные параметры алгоритма scrypt.

ERR_CRYPTO_INVALID_STATE

Метод crypto был использован на объекте, который находился в недопустимом состоянии. Например, вызов cipher.getAuthTag() перед вызовом cipher.final().

ERR_CRYPTO_INVALID_TAG_LENGTH

Была указана недопустимая длина тега аутентификации.

ERR_CRYPTO_JOB_INIT_FAILED

Инициализация асинхронной криптооперации не удалась.

ERR_CRYPTO_JWK_UNSUPPORTED_CURVE

Эллиптическая кривая ключа не зарегистрирована для использования в JSON Web Key Elliptic Curve Registry.

ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE

Асимметричный тип ключа не зарегистрирован для использования в JSON Web Key Types Registry.

ERR_CRYPTO_OPERATION_FAILED

Криптооперация завершилась неудачно по неустановленной причине.

ERR_CRYPTO_PBKDF2_ERROR

Алгоритм PBKDF2 не сработал по неустановленным причинам. OpenSSL не предоставляет более подробной информации, и, соответственно, Node.js тоже.

ERR_CRYPTO_SCRYPT_INVALID_PARAMETER

Один или несколько параметров crypto.scrypt() или crypto.scryptSync() находятся вне своего законного диапазона.

ERR_CRYPTO_SCRYPT_NOT_SUPPORTED

Node.js был скомпилирован без поддержки scrypt. Невозможно с двоичными файлами официального релиза, но может произойти с пользовательскими сборками, включая сборки дистрибутивов.

ERR_CRYPTO_SIGN_KEY_REQUIRED

Методу sign.sign() не был предоставлен ключ подписи.

ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH

crypto.timingSafeEqual() был вызван с аргументами Buffer, TypedArray или DataView разной длины.

ERR_CRYPTO_UNKNOWN_CIPHER

Был указан неизвестный шифр.

ERR_CRYPTO_UNKNOWN_DH_GROUP

Указано неизвестное имя группы Диффи-Хеллмана. Список допустимых имен групп см. в crypto.getDiffieHellman().

ERR_CRYPTO_UNSUPPORTED_OPERATION

Была предпринята попытка вызвать неподдерживаемую криптооперацию.

ERR_DEBUGGER_ERROR

Произошла ошибка при работе с отладчиком.

ERR_DEBUGGER_STARTUP_ERROR

Отладчик затянул время, ожидая, пока освободится требуемый хост/порт.

ERR_DLOPEN_DISABLED

Загрузка родных аддонов была отключена с помощью --no-addons.

ERR_DLOPEN_FAILED

Вызов process.dlopen() не удался.

ERR_DIR_CLOSED

Каталог fs.Dir был ранее закрыт.

ERR_DIR_CONCURRENT_OPERATION

A synchronous read or close call was attempted on an fs.Dir which has ongoing asynchronous operations.

ERR_DNS_SET_SERVERS_FAILED

c-ares failed to set the DNS server.

ERR_DOMAIN_CALLBACK_NOT_AVAILABLE

The node:domain module was not usable since it could not establish the required error handling hooks, because process.setUncaughtExceptionCaptureCallback() had been called at an earlier point in time.

ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE

process.setUncaughtExceptionCaptureCallback() could not be called because the node:domain module has been loaded at an earlier point in time.

The stack trace is extended to include the point in time at which the node:domain module had been loaded.

ERR_DUPLICATE_STARTUP_SNAPSHOT_MAIN_FUNCTION

v8.startupSnapshot.setDeserializeMainFunction() could not be called because it had already been called before.

ERR_ENCODING_INVALID_ENCODED_DATA

Data provided to TextDecoder() API was invalid according to the encoding provided.

ERR_ENCODING_NOT_SUPPORTED

Encoding provided to TextDecoder() API was not one of the WHATWG Supported Encodings.

ERR_EVAL_ESM_CANNOT_PRINT

--print cannot be used with ESM input.

ERR_EVENT_RECURSION

Thrown when an attempt is made to recursively dispatch an event on EventTarget.

ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE

The JS execution context is not associated with a Node.js environment. This may occur when Node.js is used as an embedded library and some hooks for the JS engine are not set up properly.

ERR_FALSY_VALUE_REJECTION

A Promise that was callbackified via util.callbackify() was rejected with a falsy value.

ERR_FEATURE_UNAVAILABLE_ON_PLATFORM

Used when a feature that is not available to the current platform which is running Node.js is used.

ERR_FS_CP_DIR_TO_NON_DIR

An attempt was made to copy a directory to a non-directory (file, symlink, etc.) using fs.cp().

ERR_FS_CP_EEXIST

An attempt was made to copy over a file that already existed with fs.cp(), with the force and errorOnExist set to true.

ERR_FS_CP_EINVAL

When using fs.cp(), src or dest pointed to an invalid path.

ERR_HTTP_CONTENT_LENGTH_MISMATCH

Response body size doesn’t match with the specified content-length header value.

ERR_FS_CP_FIFO_PIPE

An attempt was made to copy a named pipe with fs.cp().

ERR_FS_CP_NON_DIR_TO_DIR

An attempt was made to copy a non-directory (file, symlink, etc.) to a directory using fs.cp().

ERR_FS_CP_SOCKET

An attempt was made to copy to a socket with fs.cp().

ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY

When using fs.cp(), a symlink in dest pointed to a subdirectory of src.

ERR_FS_CP_UNKNOWN

An attempt was made to copy to an unknown file type with fs.cp().

ERR_FS_EISDIR

Path is a directory.

ERR_FS_FILE_TOO_LARGE

An attempt has been made to read a file whose size is larger than the maximum allowed size for a Buffer.

ERR_FS_INVALID_SYMLINK_TYPE

An invalid symlink type was passed to the fs.symlink() or fs.symlinkSync() methods.

An attempt was made to add more headers after the headers had already been sent.

An invalid HTTP header value was specified.

ERR_HTTP_INVALID_STATUS_CODE

Status code was outside the regular status code range (100-999).

ERR_HTTP_REQUEST_TIMEOUT

The client has not sent the entire request within the allowed time.

ERR_HTTP_SOCKET_ENCODING

Changing the socket encoding is not allowed per RFC 7230 Section 3.

ERR_HTTP_TRAILER_INVALID

The Trailer header was set even though the transfer encoding does not support that.

ERR_HTTP2_ALTSVC_INVALID_ORIGIN

HTTP/2 ALTSVC frames require a valid origin.

ERR_HTTP2_ALTSVC_LENGTH

HTTP/2 ALTSVC frames are limited to a maximum of 16,382 payload bytes.

For HTTP/2 requests using the CONNECT method, the :authority pseudo-header is required.

ERR_HTTP2_CONNECT_PATH

For HTTP/2 requests using the CONNECT method, the :path pseudo-header is forbidden.

ERR_HTTP2_CONNECT_SCHEME

For HTTP/2 requests using the CONNECT method, the :scheme pseudo-header is forbidden.

ERR_HTTP2_ERROR

A non-specific HTTP/2 error has occurred.

ERR_HTTP2_GOAWAY_SESSION

New HTTP/2 Streams may not be opened after the Http2Session has received a GOAWAY frame from the connected peer.

Multiple values were provided for an HTTP/2 header field that was required to have only a single value.

An additional headers was specified after an HTTP/2 response was initiated.

An attempt was made to send multiple response headers.

ERR_HTTP2_INFO_STATUS_NOT_ALLOWED

Informational HTTP status codes (1xx) may not be set as the response status code on HTTP/2 responses.

HTTP/1 connection specific headers are forbidden to be used in HTTP/2 requests and responses.

An invalid HTTP/2 header value was specified.

ERR_HTTP2_INVALID_INFO_STATUS

An invalid HTTP informational status code has been specified. Informational status codes must be an integer between 100 and 199 (inclusive).

ERR_HTTP2_INVALID_ORIGIN

HTTP/2 ORIGIN frames require a valid origin.

ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH

Input Buffer and Uint8Array instances passed to the http2.getUnpackedSettings() API must have a length that is a multiple of six.

Only valid HTTP/2 pseudoheaders (:status, :path, :authority, :scheme, and :method) may be used.

ERR_HTTP2_INVALID_SESSION

An action was performed on an Http2Session object that had already been destroyed.

ERR_HTTP2_INVALID_SETTING_VALUE

An invalid value has been specified for an HTTP/2 setting.

ERR_HTTP2_INVALID_STREAM

An operation was performed on a stream that had already been destroyed.

ERR_HTTP2_MAX_PENDING_SETTINGS_ACK

Whenever an HTTP/2 SETTINGS frame is sent to a connected peer, the peer is required to send an acknowledgment that it has received and applied the new SETTINGS. By default, a maximum number of unacknowledged SETTINGS frames may be sent at any given time. This error code is used when that limit has been reached.

ERR_HTTP2_NESTED_PUSH

An attempt was made to initiate a new push stream from within a push stream. Nested push streams are not permitted.

ERR_HTTP2_NO_MEM

Out of memory when using the http2session.setLocalWindowSize(windowSize) API.

ERR_HTTP2_NO_SOCKET_MANIPULATION

An attempt was made to directly manipulate (read, write, pause, resume, etc.) a socket attached to an Http2Session.

ERR_HTTP2_ORIGIN_LENGTH

HTTP/2 ORIGIN frames are limited to a length of 16382 bytes.

ERR_HTTP2_OUT_OF_STREAMS

The number of streams created on a single HTTP/2 session reached the maximum limit.

ERR_HTTP2_PAYLOAD_FORBIDDEN

A message payload was specified for an HTTP response code for which a payload is forbidden.

ERR_HTTP2_PING_CANCEL

An HTTP/2 ping was canceled.

ERR_HTTP2_PING_LENGTH

HTTP/2 ping payloads must be exactly 8 bytes in length.

An HTTP/2 pseudo-header has been used inappropriately. Pseudo-headers are header key names that begin with the : prefix.

ERR_HTTP2_PUSH_DISABLED

An attempt was made to create a push stream, which had been disabled by the client.

ERR_HTTP2_SEND_FILE

An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send a directory.

ERR_HTTP2_SEND_FILE_NOSEEK

An attempt was made to use the Http2Stream.prototype.responseWithFile() API to send something other than a regular file, but offset or length options were provided.

ERR_HTTP2_SESSION_ERROR

The Http2Session closed with a non-zero error code.

ERR_HTTP2_SETTINGS_CANCEL

The Http2Session settings canceled.

ERR_HTTP2_SOCKET_BOUND

An attempt was made to connect a Http2Session object to a net.Socket or tls.TLSSocket that had already been bound to another Http2Session object.

ERR_HTTP2_SOCKET_UNBOUND

An attempt was made to use the socket property of an Http2Session that has already been closed.

ERR_HTTP2_STATUS_101

Use of the 101 Informational status code is forbidden in HTTP/2.

ERR_HTTP2_STATUS_INVALID

An invalid HTTP status code has been specified. Status codes must be an integer between 100 and 599 (inclusive).

ERR_HTTP2_STREAM_CANCEL

An Http2Stream was destroyed before any data was transmitted to the connected peer.

ERR_HTTP2_STREAM_ERROR

A non-zero error code was been specified in an RST_STREAM frame.

ERR_HTTP2_STREAM_SELF_DEPENDENCY

When setting the priority for an HTTP/2 stream, the stream may be marked as a dependency for a parent stream. This error code is used when an attempt is made to mark a stream and dependent of itself.

ERR_HTTP2_TOO_MANY_INVALID_FRAMES

The limit of acceptable invalid HTTP/2 protocol frames sent by the peer, as specified through the maxSessionInvalidFrames option, has been exceeded.

ERR_HTTP2_TRAILERS_ALREADY_SENT

Trailing headers have already been sent on the Http2Stream.

ERR_HTTP2_TRAILERS_NOT_READY

The http2stream.sendTrailers() method cannot be called until after the 'wantTrailers' event is emitted on an Http2Stream object. The 'wantTrailers' event will only be emitted if the waitForTrailers option is set for the Http2Stream.

ERR_HTTP2_UNSUPPORTED_PROTOCOL

http2.connect() was passed a URL that uses any protocol other than http: or https:.

ERR_ILLEGAL_CONSTRUCTOR

An attempt was made to construct an object using a non-public constructor.

ERR_IMPORT_ASSERTION_TYPE_FAILED

An import assertion has failed, preventing the specified module to be imported.

ERR_IMPORT_ASSERTION_TYPE_MISSING

An import assertion is missing, preventing the specified module to be imported.

ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED

An import assertion is not supported by this version of Node.js.

ERR_INCOMPATIBLE_OPTION_PAIR

An option pair is incompatible with each other and cannot be used at the same time.

ERR_INPUT_TYPE_NOT_ALLOWED

Stability: 1 — Experimental

The --input-type flag was used to attempt to execute a file. This flag can only be used with input via --eval, --print, or STDIN.

ERR_INSPECTOR_ALREADY_ACTIVATED

While using the node:inspector module, an attempt was made to activate the inspector when it already started to listen on a port. Use inspector.close() before activating it on a different address.

ERR_INSPECTOR_ALREADY_CONNECTED

While using the node:inspector module, an attempt was made to connect when the inspector was already connected.

ERR_INSPECTOR_CLOSED

While using the node:inspector module, an attempt was made to use the inspector after the session had already closed.

ERR_INSPECTOR_COMMAND

An error occurred while issuing a command via the node:inspector module.

ERR_INSPECTOR_NOT_ACTIVE

The inspector is not active when inspector.waitForDebugger() is called.

ERR_INSPECTOR_NOT_AVAILABLE

The node:inspector module is not available for use.

ERR_INSPECTOR_NOT_CONNECTED

While using the node:inspector module, an attempt was made to use the inspector before it was connected.

ERR_INSPECTOR_NOT_WORKER

An API was called on the main thread that can only be used from the worker thread.

ERR_INTERNAL_ASSERTION

There was a bug in Node.js or incorrect usage of Node.js internals. To fix the error, open an issue at https://github.com/nodejs/node/issues.

ERR_INVALID_ADDRESS_FAMILY

The provided address family is not understood by the Node.js API.

ERR_INVALID_ARG_TYPE

An argument of the wrong type was passed to a Node.js API.

ERR_INVALID_ARG_VALUE

An invalid or unsupported value was passed for a given argument.

ERR_INVALID_ASYNC_ID

An invalid asyncId or triggerAsyncId was passed using AsyncHooks. An id less than -1 should never happen.

ERR_INVALID_BUFFER_SIZE

A swap was performed on a Buffer but its size was not compatible with the operation.

ERR_INVALID_CHAR

Invalid characters were detected in headers.

ERR_INVALID_CURSOR_POS

A cursor on a given stream cannot be moved to a specified row without a specified column.

ERR_INVALID_FD

A file descriptor (‘fd’) was not valid (e.g. it was a negative value).

ERR_INVALID_FD_TYPE

A file descriptor (‘fd’) type was not valid.

ERR_INVALID_FILE_URL_HOST

A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible host. This situation can only occur on Unix-like systems where only localhost or an empty host is supported.

ERR_INVALID_FILE_URL_PATH

A Node.js API that consumes file: URLs (such as certain functions in the fs module) encountered a file URL with an incompatible path. The exact semantics for determining whether a path can be used is platform-dependent.

ERR_INVALID_HANDLE_TYPE

An attempt was made to send an unsupported “handle” over an IPC communication channel to a child process. See subprocess.send() and process.send() for more information.

ERR_INVALID_HTTP_TOKEN

An invalid HTTP token was supplied.

ERR_INVALID_IP_ADDRESS

An IP address is not valid.

ERR_INVALID_MIME_SYNTAX

The syntax of a MIME is not valid.

ERR_INVALID_MODULE

An attempt was made to load a module that does not exist or was otherwise not valid.

ERR_INVALID_MODULE_SPECIFIER

The imported module string is an invalid URL, package name, or package subpath specifier.

ERR_INVALID_OBJECT_DEFINE_PROPERTY

An error occurred while setting an invalid attribute on the property of an object.

ERR_INVALID_PACKAGE_CONFIG

An invalid package.json file failed parsing.

ERR_INVALID_PACKAGE_TARGET

The package.json "exports" field contains an invalid target mapping value for the attempted module resolution.

ERR_INVALID_PERFORMANCE_MARK

While using the Performance Timing API (perf_hooks), a performance mark is invalid.

ERR_INVALID_PROTOCOL

An invalid options.protocol was passed to http.request().

ERR_INVALID_REPL_EVAL_CONFIG

Both breakEvalOnSigint and eval options were set in the REPL config, which is not supported.

ERR_INVALID_REPL_INPUT

The input may not be used in the REPL. The conditions under which this error is used are described in the REPL documentation.

ERR_INVALID_RETURN_PROPERTY

Thrown in case a function option does not provide a valid value for one of its returned object properties on execution.

ERR_INVALID_RETURN_PROPERTY_VALUE

Thrown in case a function option does not provide an expected value type for one of its returned object properties on execution.

ERR_INVALID_RETURN_VALUE

Thrown in case a function option does not return an expected value type on execution, such as when a function is expected to return a promise.

ERR_INVALID_STATE

Indicates that an operation cannot be completed due to an invalid state. For instance, an object may have already been destroyed, or may be performing another operation.

ERR_INVALID_SYNC_FORK_INPUT

A Buffer, TypedArray, DataView, or string was provided as stdio input to an asynchronous fork. See the documentation for the child_process module for more information.

ERR_INVALID_THIS

A Node.js API function was called with an incompatible this value.

const urlSearchParams = new URLSearchParams(
    'foo=bar&baz=new'
);

const buf = Buffer.alloc(1);
urlSearchParams.has.call(buf, 'foo');
// Throws a TypeError with code 'ERR_INVALID_THIS'

ERR_INVALID_TRANSFER_OBJECT

An invalid transfer object was passed to postMessage().

ERR_INVALID_TUPLE

An element in the iterable provided to the WHATWG URLSearchParams constructor did not represent a [name, value] tuple – that is, if an element is not iterable, or does not consist of exactly two elements.

ERR_INVALID_URI

An invalid URI was passed.

ERR_INVALID_URL

An invalid URL was passed to the WHATWG URL constructor or the legacy url.parse() to be parsed. The thrown error object typically has an additional property 'input' that contains the URL that failed to parse.

ERR_INVALID_URL_SCHEME

An attempt was made to use a URL of an incompatible scheme (protocol) for a specific purpose. It is only used in the WHATWG URL API support in the fs module (which only accepts URLs with 'file' scheme), but may be used in other Node.js APIs as well in the future.

ERR_IPC_CHANNEL_CLOSED

An attempt was made to use an IPC communication channel that was already closed.

ERR_IPC_DISCONNECTED

An attempt was made to disconnect an IPC communication channel that was already disconnected. See the documentation for the child_process module for more information.

ERR_IPC_ONE_PIPE

An attempt was made to create a child Node.js process using more than one IPC communication channel. See the documentation for the child_process module for more information.

ERR_IPC_SYNC_FORK

An attempt was made to open an IPC communication channel with a synchronously forked Node.js process. See the documentation for the child_process module for more information.

ERR_LOADER_CHAIN_INCOMPLETE

An ESM loader hook returned without calling next() and without explicitly signaling a short circuit.

ERR_MANIFEST_ASSERT_INTEGRITY

An attempt was made to load a resource, but the resource did not match the integrity defined by the policy manifest. See the documentation for policy manifests for more information.

ERR_MANIFEST_DEPENDENCY_MISSING

An attempt was made to load a resource, but the resource was not listed as a dependency from the location that attempted to load it. See the documentation for policy manifests for more information.

ERR_MANIFEST_INTEGRITY_MISMATCH

An attempt was made to load a policy manifest, but the manifest had multiple entries for a resource which did not match each other. Update the manifest entries to match in order to resolve this error. See the documentation for policy manifests for more information.

ERR_MANIFEST_INVALID_RESOURCE_FIELD

A policy manifest resource had an invalid value for one of its fields. Update the manifest entry to match in order to resolve this error. See the documentation for policy manifests for more information.

ERR_MANIFEST_INVALID_SPECIFIER

A policy manifest resource had an invalid value for one of its dependency mappings. Update the manifest entry to match to resolve this error. See the documentation for policy manifests for more information.

ERR_MANIFEST_PARSE_POLICY

An attempt was made to load a policy manifest, but the manifest was unable to be parsed. See the documentation for policy manifests for more information.

ERR_MANIFEST_TDZ

An attempt was made to read from a policy manifest, but the manifest initialization has not yet taken place. This is likely a bug in Node.js.

ERR_MANIFEST_UNKNOWN_ONERROR

A policy manifest was loaded, but had an unknown value for its “onerror” behavior. See the documentation for policy manifests for more information.

ERR_MEMORY_ALLOCATION_FAILED

An attempt was made to allocate memory (usually in the C++ layer) but it failed.

ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE

A message posted to a MessagePort could not be deserialized in the target vm Context. Not all Node.js objects can be successfully instantiated in any context at this time, and attempting to transfer them using postMessage() can fail on the receiving side in that case.

ERR_METHOD_NOT_IMPLEMENTED

A method is required but not implemented.

ERR_MISSING_ARGS

A required argument of a Node.js API was not passed. This is only used for strict compliance with the API specification (which in some cases may accept func(undefined) but not func()). In most native Node.js APIs, func(undefined) and func() are treated identically, and the ERR_INVALID_ARG_TYPE error code may be used instead.

ERR_MISSING_OPTION

For APIs that accept options objects, some options might be mandatory. This code is thrown if a required option is missing.

ERR_MISSING_PASSPHRASE

An attempt was made to read an encrypted key without specifying a passphrase.

ERR_MISSING_PLATFORM_FOR_WORKER

The V8 platform used by this instance of Node.js does not support creating Workers. This is caused by lack of embedder support for Workers. In particular, this error will not occur with standard builds of Node.js.

ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST

An object that needs to be explicitly listed in the transferList argument is in the object passed to a postMessage() call, but is not provided in the transferList for that call. Usually, this is a MessagePort.

In Node.js versions prior to v15.0.0, the error code being used here was ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST. However, the set of transferable object types has been expanded to cover more types than MessagePort.

ERR_MODULE_NOT_FOUND

A module file could not be resolved by the ECMAScript modules loader while attempting an import operation or when loading the program entry point.

ERR_MULTIPLE_CALLBACK

A callback was called more than once.

A callback is almost always meant to only be called once as the query can either be fulfilled or rejected but not both at the same time. The latter would be possible by calling a callback more than once.

ERR_NAPI_CONS_FUNCTION

While using Node-API, a constructor passed was not a function.

ERR_NAPI_INVALID_DATAVIEW_ARGS

While calling napi_create_dataview(), a given offset was outside the bounds of the dataview or offset + length was larger than a length of given buffer.

ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT

While calling napi_create_typedarray(), the provided offset was not a multiple of the element size.

ERR_NAPI_INVALID_TYPEDARRAY_LENGTH

While calling napi_create_typedarray(), (length * size_of_element) + byte_offset was larger than the length of given buffer.

ERR_NAPI_TSFN_CALL_JS

An error occurred while invoking the JavaScript portion of the thread-safe function.

ERR_NAPI_TSFN_GET_UNDEFINED

An error occurred while attempting to retrieve the JavaScript undefined value.

ERR_NAPI_TSFN_START_IDLE_LOOP

On the main thread, values are removed from the queue associated with the thread-safe function in an idle loop. This error indicates that an error has occurred when attempting to start the loop.

ERR_NAPI_TSFN_STOP_IDLE_LOOP

Once no more items are left in the queue, the idle loop must be suspended. This error indicates that the idle loop has failed to stop.

ERR_NOT_BUILDING_SNAPSHOT

An attempt was made to use operations that can only be used when building V8 startup snapshot even though Node.js isn’t building one.

ERR_NO_CRYPTO

An attempt was made to use crypto features while Node.js was not compiled with OpenSSL crypto support.

ERR_NO_ICU

An attempt was made to use features that require ICU, but Node.js was not compiled with ICU support.

ERR_NON_CONTEXT_AWARE_DISABLED

A non-context-aware native addon was loaded in a process that disallows them.

ERR_OUT_OF_RANGE

A given value is out of the accepted range.

ERR_PACKAGE_IMPORT_NOT_DEFINED

The package.json "imports" field does not define the given internal package specifier mapping.

ERR_PACKAGE_PATH_NOT_EXPORTED

The package.json "exports" field does not export the requested subpath. Because exports are encapsulated, private internal modules that are not exported cannot be imported through the package resolution, unless using an absolute URL.

ERR_PARSE_ARGS_INVALID_OPTION_VALUE

When strict set to true, thrown by util.parseArgs() if a {boolean} value is provided for an option of type {string}, or if a {string} value is provided for an option of type {boolean}.

ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL

Thrown by util.parseArgs(), when a positional argument is provided and allowPositionals is set to false.

ERR_PARSE_ARGS_UNKNOWN_OPTION

When strict set to true, thrown by util.parseArgs() if an argument is not configured in options.

ERR_PERFORMANCE_INVALID_TIMESTAMP

An invalid timestamp value was provided for a performance mark or measure.

ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS

Invalid options were provided for a performance measure.

ERR_PROTO_ACCESS

Accessing Object.prototype.__proto__ has been forbidden using --disable-proto=throw. Object.getPrototypeOf and Object.setPrototypeOf should be used to get and set the prototype of an object.

ERR_REQUIRE_ESM

Stability: 1 — Experimental

An attempt was made to require() an ES Module.

ERR_SCRIPT_EXECUTION_INTERRUPTED

Script execution was interrupted by SIGINT (For example, Ctrl+C was pressed.)

ERR_SCRIPT_EXECUTION_TIMEOUT

Script execution timed out, possibly due to bugs in the script being executed.

ERR_SERVER_ALREADY_LISTEN

The server.listen() method was called while a net.Server was already listening. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances.

ERR_SERVER_NOT_RUNNING

The server.close() method was called when a net.Server was not running. This applies to all instances of net.Server, including HTTP, HTTPS, and HTTP/2 Server instances.

ERR_SOCKET_ALREADY_BOUND

An attempt was made to bind a socket that has already been bound.

ERR_SOCKET_BAD_BUFFER_SIZE

An invalid (negative) size was passed for either the recvBufferSize or sendBufferSize options in dgram.createSocket().

ERR_SOCKET_BAD_PORT

An API function expecting a port >= 0 and < 65536 received an invalid value.

ERR_SOCKET_BAD_TYPE

An API function expecting a socket type (udp4 or udp6) received an invalid value.

ERR_SOCKET_BUFFER_SIZE

While using dgram.createSocket(), the size of the receive or send Buffer could not be determined.

ERR_SOCKET_CLOSED

An attempt was made to operate on an already closed socket.

ERR_SOCKET_CLOSED_BEFORE_CONNECTION

When calling net.Socket.write() on a connecting socket and the socket was closed before the connection was established.

ERR_SOCKET_DGRAM_IS_CONNECTED

A dgram.connect() call was made on an already connected socket.

ERR_SOCKET_DGRAM_NOT_CONNECTED

A dgram.disconnect() or dgram.remoteAddress() call was made on a disconnected socket.

ERR_SOCKET_DGRAM_NOT_RUNNING

A call was made and the UDP subsystem was not running.

ERR_SRI_PARSE

A string was provided for a Subresource Integrity check, but was unable to be parsed. Check the format of integrity attributes by looking at the Subresource Integrity specification.

ERR_STREAM_ALREADY_FINISHED

A stream method was called that cannot complete because the stream was finished.

ERR_STREAM_CANNOT_PIPE

An attempt was made to call stream.pipe() on a Writable stream.

ERR_STREAM_DESTROYED

A stream method was called that cannot complete because the stream was destroyed using stream.destroy().

ERR_STREAM_NULL_VALUES

An attempt was made to call stream.write() with a null chunk.

ERR_STREAM_PREMATURE_CLOSE

An error returned by stream.finished() and stream.pipeline(), when a stream or a pipeline ends non gracefully with no explicit error.

ERR_STREAM_PUSH_AFTER_EOF

An attempt was made to call stream.push() after a null(EOF) had been pushed to the stream.

ERR_STREAM_UNSHIFT_AFTER_END_EVENT

An attempt was made to call stream.unshift() after the 'end' event was emitted.

ERR_STREAM_WRAP

Prevents an abort if a string decoder was set on the Socket or if the decoder is in objectMode.

const Socket = require('node:net').Socket;
const instance = new Socket();

instance.setEncoding('utf8');

ERR_STREAM_WRITE_AFTER_END

An attempt was made to call stream.write() after stream.end() has been called.

ERR_STRING_TOO_LONG

An attempt has been made to create a string longer than the maximum allowed length.

ERR_SYNTHETIC

An artificial error object used to capture the call stack for diagnostic reports.

ERR_SYSTEM_ERROR

An unspecified or non-specific system error has occurred within the Node.js process. The error object will have an err.info object property with additional details.

ERR_TAP_LEXER_ERROR

An error representing a failing lexer state.

ERR_TAP_PARSER_ERROR

An error representing a failing parser state. Additional information about the token causing the error is available via the cause property.

ERR_TAP_VALIDATION_ERROR

This error represents a failed TAP validation.

ERR_TEST_FAILURE

This error represents a failed test. Additional information about the failure is available via the cause property. The failureType property specifies what the test was doing when the failure occurred.

ERR_TLS_CERT_ALTNAME_FORMAT

This error is thrown by checkServerIdentity if a user-supplied subjectaltname property violates encoding rules. Certificate objects produced by Node.js itself always comply with encoding rules and will never cause this error.

ERR_TLS_CERT_ALTNAME_INVALID

While using TLS, the host name/IP of the peer did not match any of the subjectAltNames in its certificate.

ERR_TLS_DH_PARAM_SIZE

While using TLS, the parameter offered for the Diffie-Hellman (DH) key-agreement protocol is too small. By default, the key length must be greater than or equal to 1024 bits to avoid vulnerabilities, even though it is strongly recommended to use 2048 bits or larger for stronger security.

ERR_TLS_HANDSHAKE_TIMEOUT

A TLS/SSL handshake timed out. In this case, the server must also abort the connection.

ERR_TLS_INVALID_CONTEXT

The context must be a SecureContext.

ERR_TLS_INVALID_PROTOCOL_METHOD

The specified secureProtocol method is invalid. It is either unknown, or disabled because it is insecure.

ERR_TLS_INVALID_PROTOCOL_VERSION

Valid TLS protocol versions are 'TLSv1', 'TLSv1.1', or 'TLSv1.2'.

ERR_TLS_INVALID_STATE

The TLS socket must be connected and securely established. Ensure the ‘secure’ event is emitted before continuing.

ERR_TLS_PROTOCOL_VERSION_CONFLICT

Attempting to set a TLS protocol minVersion or maxVersion conflicts with an attempt to set the secureProtocol explicitly. Use one mechanism or the other.

ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED

Failed to set PSK identity hint. Hint may be too long.

ERR_TLS_RENEGOTIATION_DISABLED

An attempt was made to renegotiate TLS on a socket instance with renegotiation disabled.

ERR_TLS_REQUIRED_SERVER_NAME

While using TLS, the server.addContext() method was called without providing a host name in the first parameter.

ERR_TLS_SESSION_ATTACK

An excessive amount of TLS renegotiations is detected, which is a potential vector for denial-of-service attacks.

ERR_TLS_SNI_FROM_SERVER

An attempt was made to issue Server Name Indication from a TLS server-side socket, which is only valid from a client.

ERR_TRACE_EVENTS_CATEGORY_REQUIRED

The trace_events.createTracing() method requires at least one trace event category.

ERR_TRACE_EVENTS_UNAVAILABLE

The node:trace_events module could not be loaded because Node.js was compiled with the --without-v8-platform flag.

ERR_TRANSFORM_ALREADY_TRANSFORMING

A Transform stream finished while it was still transforming.

ERR_TRANSFORM_WITH_LENGTH_0

A Transform stream finished with data still in the write buffer.

ERR_TTY_INIT_FAILED

The initialization of a TTY failed due to a system error.

ERR_UNAVAILABLE_DURING_EXIT

Function was called within a process.on('exit') handler that shouldn’t be called within process.on('exit') handler.

ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET

process.setUncaughtExceptionCaptureCallback() was called twice, without first resetting the callback to null.

This error is designed to prevent accidentally overwriting a callback registered from another module.

ERR_UNESCAPED_CHARACTERS

A string that contained unescaped characters was received.

ERR_UNHANDLED_ERROR

An unhandled error occurred (for instance, when an 'error' event is emitted by an EventEmitter but an 'error' handler is not registered).

ERR_UNKNOWN_BUILTIN_MODULE

Used to identify a specific kind of internal Node.js error that should not typically be triggered by user code. Instances of this error point to an internal bug within the Node.js binary itself.

ERR_UNKNOWN_CREDENTIAL

A Unix group or user identifier that does not exist was passed.

ERR_UNKNOWN_ENCODING

An invalid or unknown encoding option was passed to an API.

ERR_UNKNOWN_FILE_EXTENSION

Stability: 1 — Experimental

An attempt was made to load a module with an unknown or unsupported file extension.

ERR_UNKNOWN_MODULE_FORMAT

Stability: 1 — Experimental

An attempt was made to load a module with an unknown or unsupported format.

ERR_UNKNOWN_SIGNAL

An invalid or unknown process signal was passed to an API expecting a valid signal (such as subprocess.kill()).

ERR_UNSUPPORTED_DIR_IMPORT

import a directory URL is unsupported. Instead, self-reference a package using its name and define a custom subpath in the "exports" field of the package.json file.

import './'; // unsupported
import './index.js'; // supported
import 'package-name'; // supported

ERR_UNSUPPORTED_ESM_URL_SCHEME

import with URL schemes other than file and data is unsupported.

ERR_USE_AFTER_CLOSE

Stability: 1 — Experimental

An attempt was made to use something that was already closed.

ERR_VALID_PERFORMANCE_ENTRY_TYPE

While using the Performance Timing API (perf_hooks), no valid performance entry types are found.

ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING

A dynamic import callback was not specified.

ERR_VM_MODULE_ALREADY_LINKED

The module attempted to be linked is not eligible for linking, because of one of the following reasons:

  • It has already been linked (linkingStatus is 'linked')
  • It is being linked (linkingStatus is 'linking')
  • Linking has failed for this module (linkingStatus is 'errored')

ERR_VM_MODULE_CACHED_DATA_REJECTED

The cachedData option passed to a module constructor is invalid.

ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA

Cached data cannot be created for modules which have already been evaluated.

ERR_VM_MODULE_DIFFERENT_CONTEXT

The module being returned from the linker function is from a different context than the parent module. Linked modules must share the same context.

ERR_VM_MODULE_LINK_FAILURE

The module was unable to be linked due to a failure.

ERR_VM_MODULE_NOT_MODULE

The fulfilled value of a linking promise is not a vm.Module object.

ERR_VM_MODULE_STATUS

The current module’s status does not allow for this operation. The specific meaning of the error depends on the specific function.

ERR_WASI_ALREADY_STARTED

The WASI instance has already started.

ERR_WASI_NOT_STARTED

The WASI instance has not been started.

ERR_WEBASSEMBLY_RESPONSE

The Response that has been passed to WebAssembly.compileStreaming or to WebAssembly.instantiateStreaming is not a valid WebAssembly response.

ERR_WORKER_INIT_FAILED

The Worker initialization failed.

ERR_WORKER_INVALID_EXEC_ARGV

The execArgv option passed to the Worker constructor contains invalid flags.

ERR_WORKER_NOT_RUNNING

An operation failed because the Worker instance is not currently running.

ERR_WORKER_OUT_OF_MEMORY

The Worker instance terminated because it reached its memory limit.

ERR_WORKER_PATH

The path for the main script of a worker is neither an absolute path nor a relative path starting with ./ or ../.

ERR_WORKER_UNSERIALIZABLE_ERROR

All attempts at serializing an uncaught exception from a worker thread failed.

ERR_WORKER_UNSUPPORTED_OPERATION

The requested functionality is not supported in worker threads.

ERR_ZLIB_INITIALIZATION_FAILED

Creation of a zlib object failed due to incorrect configuration.

Too much HTTP header data was received. In order to protect against malicious or malconfigured clients, if more than 8 KiB of HTTP header data is received then HTTP parsing will abort without a request or response object being created, and an Error with this code will be emitted.

HPE_UNEXPECTED_CONTENT_LENGTH

Server is sending both a Content-Length header and Transfer-Encoding: chunked.

Transfer-Encoding: chunked allows the server to maintain an HTTP persistent connection for dynamically generated content. In this case, the Content-Length HTTP header cannot be used.

Use Content-Length or Transfer-Encoding: chunked.

MODULE_NOT_FOUND

Файл модуля не может быть разрешен загрузчиком модулей CommonJS при попытке выполнить операцию require() или при загрузке точки входа программы.

Legacy Node.js error codes¶

Stability: 0 — Deprecated. These error codes are either inconsistent, or have been removed.

ERR_CANNOT_TRANSFER_OBJECT

The value passed to postMessage() contained an object that is not supported for transferring.

ERR_CRYPTO_HASH_DIGEST_NO_UTF16

The UTF-16 encoding was used with hash.digest(). While the hash.digest() method does allow an encoding argument to be passed in, causing the method to return a string rather than a Buffer, the UTF-16 encoding (e.g. ucs or utf16le) is not supported.

ERR_HTTP2_FRAME_ERROR

Used when a failure occurs sending an individual frame on the HTTP/2 session.

Used when an HTTP/2 Headers Object is expected.

Used when a required header is missing in an HTTP/2 message.

HTTP/2 informational headers must only be sent prior to calling the Http2Stream.prototype.respond() method.

ERR_HTTP2_STREAM_CLOSED

Used when an action has been performed on an HTTP/2 Stream that has already been closed.

ERR_HTTP_INVALID_CHAR

Used when an invalid character is found in an HTTP response status message (reason phrase).

ERR_INDEX_OUT_OF_RANGE

A given index was out of the accepted range (e.g. negative offsets).

ERR_INVALID_OPT_VALUE

An invalid or unexpected value was passed in an options object.

ERR_INVALID_OPT_VALUE_ENCODING

An invalid or unknown file encoding was passed.

ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST

This error code was replaced by ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST in Node.js v15.0.0, because it is no longer accurate as other types of transferable objects also exist now.

ERR_NAPI_CONS_PROTOTYPE_OBJECT

Used by the Node-API when Constructor.prototype is not an object.

ERR_NETWORK_IMPORT_BAD_RESPONSE

Stability: 1 — Experimental

Response was received but was invalid when importing a module over the network.

ERR_NETWORK_IMPORT_DISALLOWED

Stability: 1 — Experimental

A network module attempted to load another module that it is not allowed to load. Likely this restriction is for security reasons.

ERR_NO_LONGER_SUPPORTED

A Node.js API was called in an unsupported manner, such as Buffer.write(string, encoding, offset[, length]).

ERR_OPERATION_FAILED

An operation failed. This is typically used to signal the general failure of an asynchronous operation.

ERR_OUTOFMEMORY

Used generically to identify that an operation caused an out of memory condition.

ERR_PARSE_HISTORY_DATA

The node:repl module was unable to parse data from the REPL history file.

ERR_SOCKET_CANNOT_SEND

Data could not be sent on a socket.

ERR_STDERR_CLOSE

An attempt was made to close the process.stderr stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code.

ERR_STDOUT_CLOSE

An attempt was made to close the process.stdout stream. By design, Node.js does not allow stdout or stderr streams to be closed by user code.

ERR_STREAM_READ_NOT_IMPLEMENTED

Used when an attempt is made to use a readable stream that has not implemented readable._read().

ERR_TLS_RENEGOTIATION_FAILED

Used when a TLS renegotiation request has failed in a non-specific way.

ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER

A SharedArrayBuffer whose memory is not managed by the JavaScript engine or by Node.js was encountered during serialization. Such a SharedArrayBuffer cannot be serialized.

This can only happen when native addons create SharedArrayBuffers in “externalized” mode, or put existing SharedArrayBuffer into externalized mode.

ERR_UNKNOWN_STDIN_TYPE

An attempt was made to launch a Node.js process with an unknown stdin file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.

ERR_UNKNOWN_STREAM_TYPE

An attempt was made to launch a Node.js process with an unknown stdout or stderr file type. This error is usually an indication of a bug within Node.js itself, although it is possible for user code to trigger it.

ERR_V8BREAKITERATOR

The V8 BreakIterator API was used but the full ICU data set is not installed.

ERR_VALUE_OUT_OF_RANGE

Used when a given value is out of the accepted range.

ERR_VM_MODULE_NOT_LINKED

The module must be successfully linked before instantiation.

ERR_VM_MODULE_LINKING_ERRORED

The linker function returned a module for which linking has failed.

ERR_WORKER_UNSUPPORTED_EXTENSION

The pathname used for the main script of a worker has an unknown file extension.

ERR_ZLIB_BINDING_CLOSED

Used when an attempt is made to use a zlib object after it has already been closed.

ERR_CPU_USAGE

Собственный вызов из process.cpuUsage не может быть обработан.


Asked by: Mr. Hans Kilback PhD

Score: 4.3/5
(29 votes)

An exception is a known type of error. An unhandled exception occurs when the application code does not properly handle exceptions. For example, When you try to open a file on disk, it is a common problem for the file to not exist. … This would cause unhandled exceptions.

How do I fix unhandled error?

How do I fix the Windows 10 unhandled exception errors?

  1. Run a virus scan. Press the Windows Key + I to open the Settings app. …
  2. Uninstall recent updates. Press the Windows key and type in view update history. …
  3. Perform a clean boot. …
  4. Run an SFC scan. …
  5. Run the hardware troubleshooter. …
  6. Uninstall and reinstall the . …
  7. Run the .

How do I fix unhandled exception in net framework?

Please try the following methods.

  1. Install the latest Windows Update.
  2. Try to use the Microsoft . NET Framework Repair Tool. …
  3. Use System File Checker to check and fix corrupted system files which may be the cause of the issue. …
  4. Enable and disable . …
  5. Uninstall and reinstall the game.
  6. Try to perform a Repair Upgrade.

How do I disable unhandled exception?

2 Answers. In the Debug menu, go to Exceptions ( Ctrl + Alt + E ). From here you can tell the debugger not to break when an exception is thrown. Just uncheck all the boxes for the lazy option, or go digging for the specific exceptions you don’t want it to break on.

What is unhandled exception caught?

According to user reports, the “Call of Duty Black Ops 2 error during initialization unhandled exception caught” message often occurs after updating to Windows 10 or installing Windows 10 updates. The error is often related to the incorrect installation of Visual C and DirectX libraries.

22 related questions found

How do I fix error during initialization unhandled exception caught?

What Causes Black Ops 2 Unhandled Exception Caught?

  1. Solution 1: Install the Proper Visual C Libraries and DirectX Versions.
  2. Solution 2: Run the Game in Compatibility Mode for Windows 8 or 7.
  3. Solution 3: Delete a File and Redownload it Using Steam.

How do you fix Black Ops 2 when it wont launch?

How can I fix Call Of Duty Black Ops 2 on Windows 10?

  1. Open Steam.
  2. Go to your library of games and locate Call of Duty Black Ops 2.
  3. Right click it and choose Uninstall. …
  4. Download the version you’ve just uninstalled, and install it again.

What causes unhandled exception?

An unhandled exception occurs when the application code does not properly handle exceptions. For example, When you try to open a file on disk, it is a common problem for the file to not exist. … This code will throw exceptions if no file path is passed in or the file does not exist. This would cause unhandled exceptions.

What does exception has occurred mean?

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.

How exceptions are used for debugging?

An exception is an indication of an error state that occurs while a program is being executed. You can tell the debugger which exceptions or sets of exceptions to break on, and at which point you want the debugger to break (that is, pause in the debugger).

How do I repair .NET framework?

Steps

  1. Close all running software applications.
  2. Go to Windows Start Menu -> Control Panel -> Add or Remove Programs or Program and Features.
  3. Select Microsoft . …
  4. Click Change/Uninstall, Remove or Repair.
  5. Select the Repair option, click Next.
  6. The wizard will perform a repair on the . …
  7. It is suggested to restart the Computer.

How do I install the latest version of .NET framework?

  1. Select Start -> Admin Tools -> Server Manager.
  2. Click the option «Features» in the window on the left-side of the screen.
  3. Select and add . NET Framework 3.5.
  4. Follow the installation process and restart the computer.

How do I update Microsoft Net Framework?

How do I update my Microsoft . NET Framework?

  1. Click the Download .NET Framework 4.6.2 Runtime button. (Do not click on the Developer Pack)
  2. Run the downloaded program. …
  3. Restart your computer when the update is finished.
  4. Launch Rocket League.

Why is NAVFIT98A not working?

Possible Cause: The user does not have the correct security permissions to the folder or file. A NAVFIT98A user must have at a minimum Read/Write permissions to a database. Open Windows Explorer, and then locate the file or folder for which you want to set permissions.

How do I disable JIT debugging?

In Windows Control Panel > Network and Internet > Internet Options, select Disable script debugging (Internet Explorer) and Disable script debugging (other).

How do I uninstall .NET framework?

Resolution

  1. Browse out to Programs and Features in Control Panel.
  2. On the left side, click on Turn Windows features on or off.
  3. Click the + symbol next to .NET framework 4.6 Advanced Services.
  4. Uncheck the ASP . …
  5. Click the OK button.
  6. Close Programs and Features window and restart the machine.

Can we make an exception?

Exempt someone or something from a general rule or practice, as in Because it’s your birthday, I’ll make an exception and let you stay up as late as you want. This expression was first recorded about 1391.

What does it mean to catch an exception?

After a method throws an exception, the runtime system attempts to find something to handle it. … An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. The exception handler chosen is said to catch the exception.

What does the JVM do when an exception occurs?

When an exception occurs, the JVM searches for catch clause related to that exception. What is the output of the following code? Describe the Java Throwable class, its subclasses, and the types of exceptions. The Throwable class is the root of exception classes.

What is the difference between exception and error?

Exceptions are those which can be handled at the run time whereas errors cannot be handled. … An Error is something that most of the time you cannot handle it. Errors are unchecked exception and the developer is not required to do anything with these.

Which event is used for unhandled exception?

The UnhandledException event is raised for unhandled exceptions thrown in other threads. Starting with Microsoft Visual Studio 2005, the Visual Basic application framework provides another event for unhandled exceptions in the main application thread.

How can you manage the action method’s unhandled exceptions?

In ASP.NET MVC we have a larger list of ways to handle exception such as:

  1. Try-catch-finally.
  2. Overriding OnException method.
  3. Using the [HandleError] attribute on actions and controllers.
  4. Setting a global exception handling filter.
  5. Handling Application_Error event.
  6. Extending HandleErrorAttribute.

Why does Black Ops 2 Zombies freeze PC?

Its possible that your disc is damaged. This happened to my Black Ops 1 disc, it would always freeze when loading certain maps. If so, try taking it somewhere to get the disc cleaned. Reset your system cache(go to system settings, storage, yellow button, clear system cache.)

Can Windows 10 play Black Ops?

Call of Duty: Black Ops Cold War Windows 10 Compatibility

These versions of Windows 10 are known to cause stability issues with Call of Duty: Black Ops Cold War and are not supported by the game as they are no longer supported by Microsoft. We recommend upgrading Windows 10 to Windows version 1803 or newer.

Which version of .NET framework comes with Windows 10?

Windows 10 (all editions) includes the . NET Framework 4.6 as an OS component, and it is installed by default. It also includes the . NET Framework 3.5 SP1 as an OS component that is not installed by default.

@coreybruce

Describe the bug
A clear and concise description of what the bug is.

Unable to download videos, Error! Unhandled error (execa). I am using the AUR package http://aur.archlinux.org/packages/youtube-dl-gui

To Reproduce
Steps to reproduce the behavior:
Tried to download any video

Expected behavior
Downloads video

Screenshots
image

image

Additional info (please complete the following information):

  • OS: Manjaro gnome
  • Application version 2.4.0-2
  • Application type AUR package

Additional context
Add any other context about the problem here.

@rulzAT

@coreybruce

For me this worked #354

I’m sorry but this doesn’t help or apply to Linux users. only Mac and Windows user specifically.

@cappuccinocosmico

Had this exact same error on manjaro, the fix for me was copying over a system binary of yt-dlp like so

sudo pacman -S yt-dlp

cp /bin/yt-dlp ~/.youtube-dl-gui/yt-dlp-unix

its a total stopgap but it works now at least.

@coreybruce

Had this exact same error on manjaro, the fix for me was copying over a system binary of yt-dlp like so

sudo pacman -S yt-dlp

cp /bin/yt-dlp ~/.youtube-dl-gui/yt-dlp-unix

its a total stopgap but it works now at least.

Wow that does fix it but yeah is only a workaround so I hop they fix this weird issue

@olegshulyakov

@daylightdev

On Windows I fixed this, Downloading «youtube-dl.exe» from original repository, renaming to «yt-dlp.exe» and place in «open-video-downloader» folder. (I used portable version).

@hashblen

I just used powershell -Command "Invoke-WebRequest https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe -OutFile %LOCALAPPDATA%Programsyoutube-dl-guiresourcesapp.asar.unpackedbinariesyt-dlp.exe" to download it and put it in the right folder on windows. The same on linux, just donwload yt-dlp and put it in the binairies fodler.

@coreybruce

But has it been fixed for Linux?

@hayguen

looks, there are a bunch of duplicates for this issue, which all have same or similar workaround — just depending on operating system:
#387
#389
#390
#392
#413
#414
#418
#431

would be great to clean up the issue list! please close the listed issues above

i fear, that this project might got abandoned by the author, see #407
are there other persons with rights to close issues — except the individual issue submitters?

@hayguen

@nleitao

Had this exact same error on manjaro, the fix for me was copying over a system binary of yt-dlp like so

sudo pacman -S yt-dlp

cp /bin/yt-dlp ~/.youtube-dl-gui/yt-dlp-unix

its a total stopgap but it works now at least.

This worked for me! thanks @cappuccinocosmico

The throw er; // unhandled ‘error’ event error usually appears if you run two servers using the same port, multiple nodes, or IIS using the same port. This error can occur while working on Node app.js, express app, or React.throw er unhandled error event

This article includes every solution to this error along with experts’ suggestions. Keep reading this article to know every detail about this error.

Contents

  • Why Am I Getting Throw ER; // Unhandled ‘Error’ Event Error?
    • – Running Another Server Using the Same Port
    • – React
    • – JSON Server in React App
  • How To Fix the Throw ER; // Unhandled ‘Error’ Event Error?
    • – Restart the App
    • – Kill the Process
    • – Change the Path
    • – Stop All Other Nodes Using That Port
    • – Change the Port
    • – Some Quick Solutions for React
    • – Remove All Packages and the Lock File, and Reinstall Everything
    • – Some Quick Solutions for Json Server in React App
    • – Use a Different ADB Device
    • – Stop the IIS Server or Stop
  • Conclusion

Why Am I Getting Throw ER; // Unhandled ‘Error’ Event Error?

Your ae getting throw er; // unhandled ‘error’ event error because of running another server using the same port, Linux or nodeJS not running as root, many nodes or IIS using the same port. This can appear while running an application with Node app.js, express app, or creating the app.

Let’s see what causes leads you to that error so that we can understand the solutions to each of them described in the next session.

– Running Another Server Using the Same Port

You can encounter this error while running an application with Node app.js that is created with expressjs if the following commands are used.

express -e folderName

npm install ejs –save

npm install

– React

This error has been encountered by many developers while creating a React app. When you use the command prompt after the creation of the app and try to start the npm, you can face this error. This error has been received on WebStorm, IntelliJ, and Visual Studio.Throw ER Unhandled ‘Error Event Causes

Sometimes, clearing the npm cache, upgrading npm, reinstalling npm and node, or upgrading react don’t help. This application can lead your application to crash.

– JSON Server in React App

You can receive this error while trying the JSON server in React app. The most common solution is upgrading npm and node to their latest versions, killing all processes, but you might still face the same issue.

You can fix this error by restarting the app, killing the process, changing the path, stopping all the nodes using the same port, or removing all the packages and reinstalling everything. There could also be many other solutions depending on the case.



In the above section, we explored a few significant areas and causes that can lead you to that error. In this section, we will cover all the possible solutions to that error.

– Restart the App

If you see this issue while using Node app.js to run an application, you may have another server using the same port, 8080. Alternatively, it’s possible that you ran the node app in a different shell; in that case, you must restart the app. While utilizing the following, you should ensure that the port number is accessible.

netstat -tulnp | grep <port no>

Alternatively, you can use Isof:

lsof -i :<port no>

– Kill the Process

You can also get a similar error while running the express app. In that case, you must check whether it is running in any terminal. You can follow the below commands to find and kill the process.

You will find the process ID second from the left.

To terminate every node process currently active, use a single command:

ps aux | awk ‘/node/{print $2}’ | xargs kill -9

An instance is likely still active, so you can use the following command to fix it. This command is only valid if you use Linux/Ubuntu and Mac.

– Change the Path

This error can happen if you are using Linux and Nodejs is not running as root. So it would help if you changed the following:Throw ER Unhandled ‘Error Event Fixes

nodejs /path/to/script.js

To this:

sudo nodejs /path/to/script.js

This is not the best answer for a production environment, as your server or application may have security gaps if you start your service as root. But if it is a local service, you should isolate the cause.

– Stop All Other Nodes Using That Port

If the port you are using to run the script is already being used, you can come across a throw er; // unhandled ‘error’ event. So, the quick solution would be to stop all other nodes using that port. The following command can help you.

You can also use the following command, which is only helpful for the node process.

This will provide you with a list of all node processes and an ID to kill them.

If you want to kill a specific ID, the following command can help you.

– Change the Port

A few developers have found their solution by changing the port. It would help if you also gave it a try. Let’s say you have the port as follows:

app.set(‘port’, process.env.PORT || 3000);<br>

You can change it as follow. This can solve your issue.

app.set(‘port’, process.env.PORT || 8080);<br>

If you have to use the same port, you can use the kill % command in the terminal. This command will kill the background process and make the port accessible.

– Some Quick Solutions for React

You should follow the instructions to eliminate this error after creating the React app. You don’t need to follow all the steps if you find your solution in the middle.

  • First, You need to check the version of the node; if necessary, update the node and npm package manager.
  • You can try sudo npm if you are MacOS or Linux user.
  • Re-download the create-react-app with the sudo command. The problem might get fixed; if not, keep following further steps.
  • Try to create the application in a different folder.
  • Delete the node_module folder and package-lock.json, and then run npm install.
  • You can try using another port as well.
  • If nothing has worked for you, you should try yarn. Install it and rerun the create-react-app. Start the server with yarn instead of npm start.

There could also be a problem with the react-script version, so you should downgrade the react script to address that.

create-react-app my-app

cd my-app

npm install react-scripts@2.1.8

npm start

Additionally, confirm that this entry exists in the PATH environment variable.

C:Users{user_name}AppDataRoamingnpm

You can also try without using create-react-app. If this doesn’t work, there might be some issue with NodeJS, so in that case, you can use React with CDNs to get rid of throw er // unhandled ‘error’ event react.

– Remove All Packages and the Lock File, and Reinstall Everything

You can also use the following commands to remove all packages and the lock file and reinstall everything.Throw ER Unhandled ‘Error Event Solutions

rm -rf node_modules

rm package-lock.json yarn.lock

npm cache clear –force

npm install

You can also stop the addition watch process; that might also help you.

Solution: Change environment variables

This issue can be found using WSL, and in that case, you can also try adding C:WindowsSystem32 to your Environment Variables Path. Consider adding System32 to the environment path variable.

– Some Quick Solutions for Json Server in React App

You can try the following quick solutions. Any solution can solve your issue.

  • You should try killall node and npm start; your local server might start working at a port.
  • One possible way to fix the problem is to delete the node_modules directory and then run npm install to reinstall the modules.
  • You could remove the package-lock.json and node_modules directories and then run npm install to reinstall the packages.
  • One possible solution is to try running npm start as the superuser, using the command sudo npm start.
  • If you are using a Windows, you can try running the following command to kill the node.exe process:

– Use a Different ADB Device

You can use a different ADB device, such as an actual smartphone, Android Studio emulator, or Genymotion emulator. Then, run npm start in your project directory to start the server. In a new terminal tab, run react-native run-android to build and install the app on the device and then stop the server.

– Stop the IIS Server or Stop

If you are a Windows user and have the IIS web server installed on your computer, there might be conflicts with the development server when you run npm start. Usually, the development server runs on port 8080, but IIS might also use the same port. The easy solution, in this case, is to either stop the IIS server or change the port the development server is using.

To stop the IIS server, you can use the Windows service manager. Or you can specify a different port for the development server by running the following command.

This will start the server on port 8000 instead of the default port 8080. And the issue can get solved.

Conclusion

We covered all the causes and their respective solution. Down below is a short summary of all the important points discussed in this article:

  • If you are using the port already being used, you should stop all other nodes using that port.
  • You can use the kill % command to use the same port.
  • Remove all packages and the lock file and reinstall everything.

This error shouldn’t be a barrier for you in the future, but if you ever get confused, you can always return to this article and find the solution.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Понравилась статья? Поделить с друзьями:
  • Ошибка unhandled e0434352h exception at 9eac4b89h
  • Ошибка unfortunately has stopped android
  • Ошибка unexpected token doctype is not valid json
  • Ошибка unexpected store exception windows 10 что это
  • Ошибка unexpected store exception windows 10 причина