Ошибки¶
Приложения, работающие на 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
, то произошла ошибка, которую следует обработать.
const fs = require('node:fs');
fs.readFile(
'файл, который не существует',
(err, data) => {
if (err) {
console.error(
'Произошла ошибка при чтении файла!',
err
);
return;
}
// Иначе обрабатываем данные
}
);
- Когда асинхронный метод вызывается на объекте, который является
EventEmitter
, ошибки могут быть направлены в событие'error'
этого объекта.
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
.
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:
// 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
, если оно установлено.
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
, не будет присутствовать в стековых трассах:
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 SharedArrayBuffer
s 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
не может быть обработан.
Номер ошибки: | Ошибка 3021 | |
Название ошибки: | Microsoft Access Error 3021 | |
Описание ошибки: | No current record. | |
Разработчик: | Microsoft Corporation | |
Программное обеспечение: | Microsoft Access | |
Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Объяснение «Microsoft Access Error 3021»
«Microsoft Access Error 3021» также считается ошибкой во время выполнения (ошибкой). Когда дело доходит до программного обеспечения, как Microsoft Access, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. Ошибки, такие как ошибка 3021, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.
Ошибка 3021 может столкнуться с пользователями Microsoft Access, если они регулярно используют программу, также рассматривается как «No current record.». Когда появится ошибка, пользователи компьютеров смогут уведомить разработчика о наличии ошибки 3021 через отчеты об ошибках. Затем Microsoft Corporation нужно будет исправить эти ошибки в главном исходном коде и предоставить модифицированную версию для загрузки. Эта ситуация происходит из-за обновления программного обеспечения Microsoft Access является одним из решений ошибок 3021 ошибок и других проблем.
Сбой во время запуска Microsoft Access или во время выполнения, как правило, когда вы столкнетесь с «Microsoft Access Error 3021». Вот три наиболее заметные причины ошибки ошибки 3021 во время выполнения происходят:
Ошибка 3021 Crash — Ошибка 3021 остановит компьютер от выполнения обычной программной операции. Это происходит много, когда продукт (Microsoft Access) или компьютер не может обрабатывать уникальные входные данные.
Утечка памяти «Microsoft Access Error 3021» — последствия утечки памяти Microsoft Access связаны с неисправной операционной системой. Потенциальные триггеры могут быть «бесконечным циклом», или когда программа выполняет «цикл» или повторение снова и снова.
Ошибка 3021 Logic Error — Компьютерная система создает неверную информацию или дает другой результат, даже если входные данные являются точными. Обычные причины этой проблемы связаны с ошибками в обработке данных.
Большинство ошибок Microsoft Access Error 3021 являются результатом отсутствия или повреждения версии файла, установленного Microsoft Access. Как правило, решить проблему можно заменой файла Microsoft Corporation. Кроме того, некоторые ошибки Microsoft Access Error 3021 могут возникать по причине наличия неправильных ссылок на реестр. По этой причине для очистки недействительных записей рекомендуется выполнить сканирование реестра.
Распространенные сообщения об ошибках в Microsoft Access Error 3021
Обнаруженные проблемы Microsoft Access Error 3021 с Microsoft Access включают:
- «Ошибка программы Microsoft Access Error 3021. «
- «Ошибка программного обеспечения Win32: Microsoft Access Error 3021»
- «Microsoft Access Error 3021 должен быть закрыт. «
- «Файл Microsoft Access Error 3021 не найден.»
- «Microsoft Access Error 3021 не может быть найден. «
- «Проблема при запуске приложения: Microsoft Access Error 3021. «
- «Файл Microsoft Access Error 3021 не запущен.»
- «Ошибка Microsoft Access Error 3021. «
- «Ошибка пути программного обеспечения: Microsoft Access Error 3021. «
Обычно ошибки Microsoft Access Error 3021 с Microsoft Access возникают во время запуска или завершения работы, в то время как программы, связанные с Microsoft Access Error 3021, выполняются, или редко во время последовательности обновления ОС. Запись ошибок Microsoft Access Error 3021 внутри Microsoft Access имеет решающее значение для обнаружения неисправностей электронной Windows и ретрансляции обратно в Microsoft Corporation для параметров ремонта.
Создатели Microsoft Access Error 3021 Трудности
Проблемы Microsoft Access Error 3021 могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Microsoft Access Error 3021, или к вирусам / вредоносному ПО.
В частности, проблемы с Microsoft Access Error 3021, вызванные:
- Недопустимый Microsoft Access Error 3021 или поврежденный раздел реестра.
- Вирус или вредоносное ПО, повреждающее Microsoft Access Error 3021.
- Microsoft Access Error 3021 ошибочно удален или злонамеренно программным обеспечением, не связанным с приложением Microsoft Access.
- Microsoft Access Error 3021 конфликтует с другой программой (общим файлом).
- Microsoft Access (Microsoft Access Error 3021) поврежден во время загрузки или установки.
Продукт Solvusoft
Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
Содержание
- Как исправить время выполнения Ошибка 3021 Ошибка Microsoft Access 3021
- Vba runtime error 3021
- Answered by:
- Question
- Answers
- Thread: [RESOLVED] Run-Time Error ‘3021’ No Current Record Found
- [RESOLVED] Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
Как исправить время выполнения Ошибка 3021 Ошибка Microsoft Access 3021
В этой статье представлена ошибка с номером Ошибка 3021, известная как Ошибка Microsoft Access 3021, описанная как Текущих записей нет.
Информация об ошибке
Имя ошибки: Ошибка Microsoft Access 3021
Номер ошибки: Ошибка 3021
Описание: Текущих записей нет.
Программное обеспечение: Microsoft Access
Разработчик: Microsoft
Этот инструмент исправления может устранить такие распространенные компьютерные ошибки, как BSODs, зависание системы и сбои. Он может заменить отсутствующие файлы операционной системы и библиотеки DLL, удалить вредоносное ПО и устранить вызванные им повреждения, а также оптимизировать ваш компьютер для максимальной производительности.
О программе Runtime Ошибка 3021
Время выполнения Ошибка 3021 происходит, когда Microsoft Access дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.
Определения (Бета)
Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!
- Доступ — НЕ ИСПОЛЬЗУЙТЕ этот тег для Microsoft Access, используйте вместо него [ms-access]
- Запись — запись в программирование — это тип данных с метками для доступа к полям записи.
- Access . Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно объединяет реляционный Microsoft JetACE Database Engine с графическим пользовательским интерфейсом и инструментами разработки программного обеспечения.
- Microsoft Access — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft который обычно сочетает в себе реляционное ядро СУБД Microsoft JetACE с графическим пользовательским интерфейсом и инструментами разработки программного обеспечения.
Симптомы Ошибка 3021 — Ошибка Microsoft Access 3021
Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.
Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.
(Ошибка Microsoft Access 3021) Repair Tool»/>
(Только для примера)
Причины Ошибка Microsoft Access 3021 — Ошибка 3021
При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.
Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.
Методы исправления
Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.
Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.
Источник
Vba runtime error 3021
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
Run-time Error 3021: No Current Record
I get this error while I try to Import Excel file in one of the MS Access tables using VBA. Attaching screenshot, how to solve this please??
Just to be clear, I’ve made sure «tblBoQ» table and «C:ImportBoQ» Excel files are at place. So there’s no question about it.
Answers
>>>. but now when I split the table in a FE/BE scenario, it gives me below error. Why is it so please??
According to your description, I have reproduced this issue. Regarding this issue, based on my research, two main reasons for the occurrence of the above error message are discussed below:
1. Appending of the records that were the primary key values
2. Violating referential integrity rules for a relationship defined between tables
You could use Get External Data wizard to import Excel file, after you have completed the Import wizard, Access notifies you of any problems that might have occurred during the import process. In some cases, Access might create a new table called ImportErrors, which contains any data that it was unable to import successfully. You can examine the data in this table to try to find out why the data did not import correctly.
For more information, click here to refer about Introduction to importing and exporting data
Источник
Thread: [RESOLVED] Run-Time Error ‘3021’ No Current Record Found
Thread Tools
Display
[RESOLVED] Run-Time Error ‘3021’ No Current Record Found
I’ve read through the other threads on this topic but they don’t seem to apply to my problem. I have a 1 row table that I’m trying to read into a recordset using VB6, but when I try to access any of the fields in the record, I get a runtime error 3021 «No current record».
I thought that when you use the Set Recordset command the recordset is populated with the contents of the target table. But that’s not happening. Can someone tell me what I’m doing wrong? Any help is greatly appreciated. Here’s my code:
Database: MS Access
Field: mpSalesRankTier1
Data type: Number
Content: 10000
Number of rows in table: 1
Last edited by vb6coder14; Oct 20th, 2014 at 01:03 PM .
Re: Run-Time Error ‘3021’ No Current Record Found
It looks like you are using DAO
Then:
1 Reference the DAO library
2 Change the lines where you declare and where you open Recordset
. If your problem is fixed don’t forget to mark your threads as resolved using the Thread Tools menu .
Re: Run-Time Error ‘3021’ No Current Record Found
jggtz, I made all of the changes you suggested and no dice. I’m still getting the same problem.
Re: Run-Time Error ‘3021’ No Current Record Found
I happen to still use the DAO often. vb6coder14, with the DAO, it’s possible to have the recordset sitting on a non-record, and that’s exactly the case when you initially open a recordset.
All that’s necessary is that you execute a rsCtrlRec.MoveFirst command before you try and read the fields.
Be careful though. That will also throw an error if there are no records in the table. If you also want to avoid that, do something like «If rsCtrlRec.RecordCount > 0 Then . «
Re: Run-Time Error ‘3021’ No Current Record Found
It’s been a while since I have done DAO, so these are only observations, but here it goes..
1- dim rsCtrlRec as RecordSet is valid if your DAO reference is set correctly. (no need for DAO.)
2- Set rsCtrlRec = dbCtrlRec.OpenRecordset(«SYS_CONTROL_RECORD») is ok too
3- I always use indexed recordset, and by habit, I always include the line :
to avoid BOF conditions
4- Make sure you have records :
5- check the position of the record pointer with rsCtrlRec.BOF and rsCtrlRec.EOF when encountering problems such as you have. For example, if you have no records, after opening the recordset :
rsCtrlRec.MoveFirst
if rsCtrlRec.BOF then
rem there are no records
end if
6- and last, but it should have been the first point mentioned, are you sure there is not typo in your field name, and that the field indeed does exist.. you can get the value of a field by its index number instead of a literal
will return the value for the first field in the table, no matter what it’s literal name is. this will also indicate that you have indeed at least one field defined if no error is returned.
Re: Run-Time Error ‘3021’ No Current Record Found
Navion, you can use .MoveFirst, .MoveNext, .MovePrev, and .MoveLast without an index. There’s just no guarantee of the order of the records.
With no index, you just don’t get the use of .Seek. which is where the real power is.
Re: Run-Time Error ‘3021’ No Current Record Found
vb6coder14, here’s the DAO help file, in case you don’t have it. As Navion hinted, also be sure to learn the meaning of .BOF and .EOF. If you’re just using an .MDB style database, I’ve found the DAO to be an incredibly powerful tool. Elegant, bulletproof, and simple.
Re: Run-Time Error ‘3021’ No Current Record Found
Yeah sure. Except for a generic SQL handler program I have written way back then (i still use it and it never required any updating ever since) that used non indexed tables, all the rest of my work uses indexes and since my code rarely fails if ever , I keep methods that have proven their worth , even if things could be done some other ways.
Old habits die hard. For example, I never use :
Dim a as String
It will always be
for me although I am not real strong on Option Explicit why bother and be nagged countless times. I can keep track of variables on my own loll
When you put too much restrictions on coding, it becomes VB 2010 and I don’t wish that anyone
Re: Run-Time Error ‘3021’ No Current Record Found
Hey Navion, I’m totally with you. I mostly work alone these days, but I’ve had to fire programmers in the past who wouldn’t leave unbroken code alone. If it ain’t broke, DON’T FIX IT! There’s another «code sharing» thread on here where I made a similar point. The sharing of .BAS (or other) files in multiple .VBP project is a monumentally bad idea in my opinion. It’s the same issue, someone «fixing» code for one project that breaks another.
I’ll have to admit that I go back to the a!, a$, and a# days, but I have managed to wean myself into the new «as string» etc format. The only similar habit that I won’t break is Left$(s, 4), Mid$(s, 2, 5), etc. I do use variants and even like them, but I do stay away from them whenever possible. (Just noting that Left(s,4) returns a variant whereas Left$(s,4) returns a string.
Oh geez, I’m a HUGE advocate of Option Explicit. SOOO many times before we had it, I can remember beating my head against the wall, when it was just a variable name typo. In fact, I’ve long advocated that there should also be an Option TypeExplicit that applied to Redim as well as functions. I mean, if I want a variant or a late bound object, I’ll declare it as such.
I’ll agree that they should stay the meta-commands (Option . ), but they do make finding bugs easier.
Re: Run-Time Error ‘3021’ No Current Record Found
Its been a while since I have used DAO but I do not remember ever needing to issue a movefirst to get to an active record when a recordset is first opened.
Of course there is no code there that checks to see if any records were returned so my guess would be that movefirst would also throw an error as I suspect the problem is that the recordset is empty
Re: Run-Time Error ‘3021’ No Current Record Found
You know what, DataMiser? You’re right. I guess I’ve just never thought to NOT do a .MoveFirst. I just tested it and the recordset opens on the first record. Actually, all of my tables DO have indices (including PrimaryKey indices), so I’m not sure what happens on tables without an index, but that’s interesting.
Re: Run-Time Error ‘3021’ No Current Record Found
I do not think the presence of or absence of indexes/primary keys would have any effect either.
They will of course make your queries faster when using criteria that is indexed but as far as moving next, previous, first, last I would not expect there to be any difference.
Re: Run-Time Error ‘3021’ No Current Record Found
DataMiser is right. The recordset is empty. What threw me was my lack of understanding of the internal workings of a .MDB file. I actually manually keyed values into the database, but I didn’t hit the ENTER key. I went straight to SAVE. Consequently, although it appeared as if I had data, I really didn’t.
It wasn’t until I physically went back into the database and hit the ENTER key when a 2nd record appeared, this one prefixed with an ‘*’. I’m going to assume that’s the EOF pointer. When I ran my code again, it worked just fine.
Can someone confirm my interpretation of what happened, or am I still off base in my understanding?
Re: Run-Time Error ‘3021’ No Current Record Found
I wrote a paper back in the early days of VB, when they introduced Variants as the default data , destroying old myths and urban legends about stronger typed variables from old time programmers (although I am one of those myself). I do like variants but I use Typed variables too a lot, most often than not actually.
At some point, I got a bit lazy and started to use the variant versions of the common string functions too. but not anymore. they are slower and introduce an element of uncertainty (in my mind anyway, no real rationale on that argument). I reverted back to the mid$ and Trim$ etc. I think readability is much improved.
I have read your posts these past few days, and between the lines too. I think we both would get along
Re: Run-Time Error ‘3021’ No Current Record Found
Before a MoveFirst is called, shouldn’t the recordset be checked for .EOF? I see that the posted code is using the generic ON ERROR GOTO [label], but checking for .EOF after returning the recordset can allow the option of using some default values vs. exiting the routine if .MoveFirst cause an error. Just thinking out loud
Insomnia is just a byproduct of, » It can’t be done»
Classics Enthusiast ? Here’s my 1969 Mustang Mach I Fastback. Her sister ’67 Coupe has been adopted
Re: Run-Time Error ‘3021’ No Current Record Found
Yep, you’re right LaVolpe, but that’s why I mentioned the RecordCount property in post #4. If it’s got records, a MoveFirst will never fail.
And a smile and nod to Navion. )) Are we all having fun now? LMAO
Re: Run-Time Error ‘3021’ No Current Record Found
A recordset, depending on type & sql provider, can have an initial value of -1 if I recall correctly
Insomnia is just a byproduct of, » It can’t be done»
Classics Enthusiast ? Here’s my 1969 Mustang Mach I Fastback. Her sister ’67 Coupe has been adopted
Re: Run-Time Error ‘3021’ No Current Record Found
Yes, but for my own common use, I use indexed tables, a movefirst (that I don’t remember throwing an error on empty recordset), followed by a seek and a NoMatch that will take care of the EOF if any. Navigating down, of course, checking EOF is required.
On error should not be really be used doing DAO, good coding should use BOF, EOF, NoMatch (index stuff). That does not leave much causes for errors
Re: Run-Time Error ‘3021’ No Current Record Found
Indeed Elroy! Indeed! Almost a chat room atmosphere. But let’s not hijack the OP’s thread too much
(for the record lolll)
Re: Run-Time Error ‘3021’ No Current Record Found
Navion, I totally agree. I have my share of On Error Resume Next, and On Error Goto . in my code, but I very seldom use it when using DAO methods. I either get it right, or I debug it.
Actually, I just looked around at some of my standard DAO procedures and did find this code:
I did put error ignoring in there, but, truth be told, I’ve now got no idea why. However, going back to something I said earlier today, if it ain’t broken, don’t fix it.
Re: Run-Time Error ‘3021’ No Current Record Found
Honestly, don’t mess with DAO much any longer, but with ADO. Per MSDN: «A call to either MoveFirst or MoveLast when the Recordset is empty (both BOF and EOF are True) generates an error.»
To avoid that situation, my general iteration of the recordset kinda looks like this
Insomnia is just a byproduct of, » It can’t be done»
Classics Enthusiast ? Here’s my 1969 Mustang Mach I Fastback. Her sister ’67 Coupe has been adopted
Re: Run-Time Error ‘3021’ No Current Record Found
Yep, I seldom let these conditions happen, but I believe that an empty recordset will set both .BOF and .EOF as true. And I think that’s the only time it happens. Also, I’m pretty sure that the DAO and the ADO are VERY similar (if not identical) regarding all of these relatively straightforward procedures.
Re: Run-Time Error ‘3021’ No Current Record Found
Funny that you should mention that Elroy, I forgot to do it myself. another essential of DAO is IsNull, particularly with binary fields, they don’t like much being cast to empty strings, although .FieldSize does the job too.
Re: Run-Time Error ‘3021’ No Current Record Found
Yes, .Recordcount will return -1 in cases where recordcount is not supported. I can’t remember if this is the case with DAO but ADO will return -1 when using a server side cursor no matter how many records there may be.
Checking for .eof is a more fool proof method.
Re: Run-Time Error ‘3021’ No Current Record Found
When using DAO .RecordCount will give you the result only after a .MoveLast method
. If your problem is fixed don’t forget to mark your threads as resolved using the Thread Tools menu .
Источник
After every execution, regardless of said execution — when using Chrome web browser the PHP local server throws this error:
Invalid request (Unexpected EOF) \n
It’s not causing any visible issues; however as it’s a persistent issue I was wondering if something may bite me later.
Any ideas?
Note: it happens roughly 10 seconds after any page is executed.
Further note: This happens after all executions, even when the files
are ended correctly:
<?php echo 'hey'; ?>
would still throw the aforementioned error.
[Thu Mar 19 09:39:55 2015] 127.0.0.1:53923 [200]: /admin
[Thu Mar 19 09:40:05 2015] 127.0.0.1:53924 Invalid request (Unexpected EOF)
This is the full error.
asked Mar 19, 2015 at 9:43
Jack hardcastleJack hardcastle
2,7564 gold badges22 silver badges41 bronze badges
6
This is a known bug.
From https://bugs.php.net/bug.php?id=60471:
[2011-12-08 15:01 UTC] lolautruche at gmail dot com Description:
————
From time to time, built-in server with router script logs this kind of stuff :[Thu Dec 8 13:39:29 2011] 127.0.0.1:50358 Invalid request (Unexpected
EOF)This happens quite randomly, whatever the script has a close tag or
not, whatever it has a blank line after close tag or not.
And the explanation:
[2012-02-23 18:45 UTC] michal dot pipa dot xsolve at gmail dot com
…
Chromium has feature called «Predict network actions to improve page
load performance» and its enabled by default. It works this way, that
if HTML page has links to some resources, than Chromium opens about
10 TCP connections in advance. And then if browser has less than 10
resources to fetch, unused connections times out after 10 seconds.
And this (empty payload) causes PHP server to display «Invalid request
(unexpected EOF)» message.
It is a harmless error from the PHP built-in server.
Sᴀᴍ Onᴇᴌᴀ
8,2188 gold badges36 silver badges58 bronze badges
answered Nov 25, 2015 at 6:12
GaryGary
2,2912 gold badges25 silver badges47 bronze badges
1
This could be related to Chrome specifically and its network prediction feature. So try to disable that feature first. That’s why it works for you in Incognito mode, because probably it’s disabled in that mode.
You can find this option in Chrome Settings and click on ‘Show advanced settings’. Should be there in Privacy section.
answered Mar 19, 2015 at 10:52
kenorbkenorb
156k88 gold badges679 silver badges743 bronze badges
5
This is bug on PHP. It was fixed on PHP 7.2
answered Nov 9, 2017 at 23:00
rscrsc
10.4k5 gold badges39 silver badges36 bronze badges
1
On Laravel, I realize this thread hasn’t been active for a while now but I found a solution completely unrelated to what other people have been posting. So I realized that I was getting this very error because I didn’t have an application key set for my application. You can find out more about application keys in this other Stack Overflow question. Before attempting to generate an application key, make sure you’ve run the following command in the root directory of your application.
composer install
From what I’ve read, when you create a new application via the
laravel new application
command, you should have a file called .env
by default. This was not my case, I had to rename the .env.example
file to .env
manually.
Once you have done the two above steps, run this command in the root directory of your app
php artisan key:generate
This solved the OP’s error for me. Hope it can help someone in the future.
answered Oct 21, 2017 at 22:47
Gaboik1Gaboik1
3633 silver badges15 bronze badges
On Laravel 4.2, I resolve that when I clear the cache with command :
php artisan cache:clear
Complete list of commands is available with :
php artisan list
answered Feb 18, 2016 at 14:25
NolwennigNolwennig
1,61324 silver badges29 bronze badges
1
I started to encounter this phenomenon just recently with both Firefox and Chrome.
I can’t confirm nor deny any problems with browser plugins.
Since I hadn’t change anything in my development environment I started to look for other possibilities.
Turns out it was the real time scan engine of the new version of my antivirus program.
Once I excluded my project build folders, the php installation folder and php.exe from the scanning the problems with sudden eof occurrences instantly vanished.
Maybe this helps some of you.
answered Oct 29, 2015 at 17:16
I confirmed that @user194714’s suggestion is indeed a reason (maybe not the only one though). I’m using WordPress 4.7.1 and changing wp-admin/about.php @ line 55 resolved this issue. More importantly, the page loaded faster after this simple change. I will let WordPress maintainers know.
answered Jan 25, 2017 at 21:07
In my case, I’m using laravel 5.1 + AngularJs and I had removed the route:
**Route::get('/', function () {
return view('app');
});**
I put this back and now it works fine.
answered May 16, 2017 at 3:40
I had this error when running PHP on port 9000; after changing it to 8000 the error disappeared.
Das_Geek
2,7837 gold badges20 silver badges26 bronze badges
answered Jan 7, 2020 at 13:44
I see this behaviour when in index.html
<script src="main.js"></script>
is replaced with
<script src="main.js" />
(instead of closing </script>
tag its short version is used />
).
answered Jun 18, 2015 at 3:38
mp31415mp31415
6,5411 gold badge44 silver badges35 bronze badges
0
Table of Contents
Hide
- What is an unexpected EOF while parsing error in Python?
- How to fix SyntaxError: unexpected EOF while parsing?
- Scenario 1 – Missing parenthesis or Unclosed parenthesis
- Scenario 2: Incomplete functions along with statements, loops, try and except
- Conclusion
The SyntaxError: unexpected EOF while parsing occurs if the Python interpreter reaches the end of your source code before executing all the code blocks. This happens if you forget to close the parenthesis or if you have forgotten to add the code in the blocks statements such as for
, if
, while
, etc. To solve this error check if all the parenthesis are closed properly and you have at least one line of code written after the statements such as for
, if
, while
, and functions.
What is an unexpected EOF while parsing error in Python?
EOF stands for End of File and SyntaxError: unexpected EOF while parsing error occurs where the control in the code reaches the end before all the code is executed.
Generally, if you forget to complete a code block in python code, you will get an error “SyntaxError: unexpected EOF while parsing.”
Most programming languages like C, C++, and Java use curly braces { }
to define a block of code. Python, on the other hand, is a “block-structured language” that uses indentation.
A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block.
There are several reasons why we get this error while writing the python code. Let us look into each of the scenarios and solve the issue.
Sometimes if the code is not indented properly you will get unindent does not match any outer indentation error.
Scenario 1 – Missing parenthesis or Unclosed parenthesis
One of the most common scenarios is an unclosed parenthesis (), brackets [], and curly braces {} in the Python code.
- Parenthesis is mainly used in print statements, declaring tuples, calling the built-in or user-defined methods, etc.
- Square brackets are used in declaring the Arrays, Lists, etc in Python
- Curly braces are mainly used in creating the dictionary and JSON objects.
In the below example, we have taken simple use cases to demonstrate the issue. In larger applications, the code will be more complex and we should use IDEs such as VS Code, and PyCharm which detect and highlights these common issues to developers.
# Paranthesis is not closed properly in the Print Statement
print("Hello"
# Square bracket is not closed while declaring the list
items =[1,2,3,4,5
# Curly Braces is not closed while creating the dictionary
dictionary={ 'FirstName':'Jack'
Output
SyntaxError: unexpected EOF while parsing
If you look at the above code, we have a print statement where the parenthesis has not closed, a list where the square bracket is not closed, and a dictionary where the curly braces are not closed. Python interpreter will raise unexpected EOF while parsing.
Solution :
We can fix the issue by enclosing the braces, parenthesis, and square brackets properly in the code as shown below.
# Paranthesis is now closed properly in the Print Statement
print("Hello")
# Square bracket is now closed while declaring the list
items =[1,2,3,4,5]
print(items)
# Curly Braces is now closed while creating the dictionary
dictionary={ 'FirstName':'Jack'}
print(dictionary)
Output
Hello
[1, 2, 3, 4, 5]
{'FirstName': 'Jack'}
If we try to execute the program notice the error is gone and we will get the output as expected.
Scenario 2: Incomplete functions along with statements, loops, try and except
The other scenario is if you have forgotten to add the code after the Python statements, loops, and methods.
- if Statement / if else Statement
- try-except statement
- for loop
- while loop
- user-defined function
Python expects at least one line of code to be present right after these statements and loops. If you have forgotten or missed to add code inside these code blocks Python will raise SyntaxError: unexpected EOF while parsing
Let us look at some of these examples to demonstrate the issue. For demonstration, all the code blocks are added as a single code snippet.
# Code is missing after the for loop
fruits = ["apple","orange","grapes","pineapple"]
for i in fruits :
# Code is missing after the if statement
a=5
if (a>10):
# Code is missing after the else statement
a=15
if (a>10):
print("Number is greater than 10")
else:
# Code is missing after the while loop
num=15
while(num<20):
# Code is missing after the method declaration
def add(a,b):
Output
SyntaxError: unexpected EOF while parsing
Solution :
We can fix the issue by addressing all the issues in each code block as mentioned below.
- for loop: We have added the print statement after the for loop.
- if else statement: After the conditional check we have added the print statement which fixes the issue.
- while loop: We have added a print statement and also incremented the counter until the loop satisfies the condition.
- method: The method definition cannot be empty we have added the print statement to fix the issue.
# For loop fixed
fruits = ["apple", "orange", "grapes", "pineapple"]
for i in fruits:
print(i)
# if statement fixed
a = 5
if a > 10:
print("number is greated than 10")
else:
print("number is lesser than 10")
# if else statement fixed
a = 15
if a > 10:
print("Number is greater than 10")
else:
print("number is lesser than 10")
# while loop fixed
num = 15
while num < 20:
print("Current Number is", num)
num = num + 1
# Method fix
def add(a, b):
print("Hello Python")
add(4, 5)
Output
apple
orange
grapes
pineapple
number is lesser than 10
Number is greater than 10
Current Number is 15
Current Number is 16
Current Number is 17
Current Number is 18
Current Number is 19
Hello Python
Conclusion
The SyntaxError: unexpected EOF while parsing
occurs if the Python interpreter reaches the end of your source code before executing all the code blocks. To resolve the SyntaxError: unexpected EOF while parsing in Python, make sure that you follow the below steps.
- Check for Proper Indentation in the code.
- Make sure all the parenthesis, brackets, and curly braces are opened and closed correctly.
- At least one statement of code exists in loops, statements, and functions.
- Verify the syntax, parameters, and the closing statements
This post was last Updated on by Himanshu Tyagi to reflect the accuracy and up-to-date information on the page.
In this tutorial, you will learn how fix unexpected EOF while parsing error in Python. Unexpected EOF while parsing error is a Syntax error and occurs when the interpreter reaches the end of the python code before any code block is complete. This error occurs when the body is not coded/included inside conditional statements (if, else), loops (for, while), functions, etc.
Below are the cases when the “Unexpected EOF While Parsing Error” occurs and also provided the ways to fix those errors.
Also Read: How To Copy List in Python
How to Fix Unexpected EOF While Parsing Error In Python
1. Fix – Unexpected EOF while parsing error when using conditional statements
Unexpected EOF while parsing error occurs in conditional statements when any if, else statement is used without a single line of the body.
Example 1: Let’s look into the sample code which throws the Unexpected EOF error while using the if statement.
Code:
number = 1 if(number==1):
Error:
File "<ipython-input-2-8cb60fd8f815>", line 2 if(number==1): ^ SyntaxError: unexpected EOF while parsing
Also Read: 10 Best Programming Apps To Learn Python
2. Fix – Unexpected EOF while parsing error when using loops
Unexpected EOF while parsing error occurs in loops when any for/while statement is used without a single line of body inside them.
Example 1: Let’s look into the sample code that throws the Unexpected EOF error while using the loop.
sum=0 # sum of 1-10 numbers for i in range(1,11): Error File "<ipython-input-7-1f8b5a6d6ae0>", line 3 for i in range(1,11): ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the for loop didn’t consist of a body/code to execute inside the loop. So to fix this error, we need to add the code block inside the for loop.
Code Fix:
sum=0 # sum of 1-10 numbers for i in range(1,11): sum=sum+i print("Sum of 1-10 numbers = ",sum)
Output:
Sum of 1-10 numbers = 55
Also Read: Python Program To Reverse A Number
Example 2: Let’s look into the sample code which throws the Unexpected EOF error while using a while loop.
Code:
number=1 # print 1 to 10 number while(i<=10):
Error:
File "<ipython-input-10-f825e1f8a55a>", line 3 while(i<=10): ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the while loop didn’t consist of a body/code to execute. So to fix this error, we need to add the code block inside the while loop.
Also Read: Python Program to Find Sum of Digits [5 Methods]
Code Fix:
number=1 # print 1 to 10 number while(number<=10): print(number,end=" ") number=number+1
Output:
1 2 3 4 5 6 7 8 9 10
Also Read: Python Program To Check If A Number Is a Perfect Square
3. Fix – Unexpected EOF while parsing error in functions
Unexpected EOF while parsing error occurs in function when any function is defined without a body or when we made syntax mistakes while calling the function.
Example 1: Let’s look into the sample code which throws the Unexpected EOF error when we define any function with no body.
Code:
def findEvenorNot(number):
Error:
File "<ipython-input-17-7cb37f6aa589>", line 1 def findEvenorNot(number): ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the function findEvenorNot is defined without anybody/code. So to fix this error, we need to add the code block inside the function.
Code Fix:
def findEvenorNot(number): if(number%2==0): print(number," is Even") else: print(number," is Odd") findEvenorNot(24)
Output:
24 is Even
Also Read: Increment and Decrement Operators in Python
Example 2: Let’s look into another sample code that throws the Unexpected EOF error when we call a function with incorrect syntax.
Code:
def findEvenorNot(number): if(number%2==0): print(number," is Even") else: print(number," is Odd") findEvenorNot(
Error:
File "<ipython-input-24-35123bc59f61>", line 7 findEvenorNot( ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred because the function call had incorrect syntax. So to fix this error, we need to call the function with proper syntax i.e., functionName(parameter1, parameter2, …..).
Also Read: Python Dictionary Length [How To Get Length]
Code Fix:
def findEvenorNot(number): if(number%2==0): print(number," is Even") else: print(number," is Odd") findEvenorNot(831)
Output:
831 is Odd
Also Read: How To Concatenate Arrays in Python [With Examples]
4. Fix – Unexpected EOF while parsing error due to missing parenthesis
Unexpected EOF while parsing error also occurs if we miss any parentheses while using any standard/user-defined functions.
Note: The above example also comes under this category.
Example: Let’s look into an example code that throws the Unexpected EOF error due to missing parenthesis.
Code:
programmingLanguages=["C", "C++","Java","Python","JS"] for lang in programmingLanguages: print(lang
Error:
File "<ipython-input-27-c9c853e4f9e6>", line 4 print(lang ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred due to closing parenthesis miss in the print statement. So to fix this error, we need to add the missing parenthesis.
Code Fix:
programmingLanguages=["C", "C++","Java","Python","JS"] for lang in programmingLanguages: print(lang)
Output:
C C++ Java Python JS
Also Read: What Does The Python Percent Sign Mean?
5. Fix – Unexpected EOF while parsing error in Try Except blocks
Unexpected EOF while parsing error also occurs if we didn’t include an except block for a try block.
Example: Let’s look into an example code that throws the Unexpected EOF error due to missing an except block for a try block.
Code:
number = 18 try: result = number/0 print(result)
Error:
File "<ipython-input-2-79e117053f09>", line 5 print(result) ^ SyntaxError: unexpected EOF while parsing
The error unexpected EOF while parsing occurred due to the absence of except block for a try block. So to fix this error, we need to include an except block for the try block.
Code Fix:
number = 18 try: result = number/0 print(result) except: print("Division by zero exception")
Output:
Division by zero exception
Also Read: How to Create an Empty Array In Python
Summary
These are some ways when the “unexpected EOF while parsing” error occurs and ways to fix the errors.
Have you seen the syntax error “unexpected EOF while parsing” when you run a Python program? Are you looking for a fix? You are in the right place.
The error “unexpected EOF while parsing” occurs when the interpreter reaches the end of a Python file before every code block is complete. This can happen, for example, if any of the following is not present: the body of a loop (for / while), the code inside an if else statement, the body of a function.
We will go through few examples that show when the “unexpected EOF while parsing” error occurs and what code you have to add to fix it.
Let’s get started!
How Do You Fix the EOF While Parsing Error in Python?
If the unexpected EOF error occurs when running a Python program, this is usually a sign that some code is missing.
This is a syntax error that shows that a specific Python statement doesn’t follow the syntax expected by the Python interpreter.
For example, when you use a for loop you have to specify one or more lines of code inside the loop.
The same applies to an if statement or to a Python function.
To fix the EOF while parsing error in Python you have to identify the construct that is not following the correct syntax and add any missing lines to make the syntax correct.
The exception raised by the Python interpreter will give you an idea about the line of code where the error has been encountered.
Once you know the line of code you can identify the potential code missing and add it in the right place (remember that in Python indentation is also important).
SyntaxError: Unexpected EOF While Parsing with a For Loop
Let’s see the syntax error that occurs when you write a for loop to go through the elements of a list but you don’t complete the body of the loop.
In a Python file called eof_for.py define the following list:
animals = ['lion', 'tiger', 'elephant']
Then write the line below:
for animal in animals:
This is what happens when you execute this code…
$ python eof_for.py
File "eof_for.py", line 4
^
SyntaxError: unexpected EOF while parsing
A SyntaxError is raised by the Python interpreter.
The exception “SyntaxError: unexpected EOF while parsing” is raised by the Python interpreter when using a for loop if the body of the for loop is missing.
The end of file is unexpected because the interpreter expects to find the body of the for loop before encountering the end of the Python code.
To get rid of the unexpected EOF while parsing error you have to add a body to the for loop. For example a single line that prints the elements of the list:
for animal in animals:
print(animal)
Update the Python program, execute it and confirm that the error doesn’t appear anymore.
Unexpected EOF While Parsing When Using an If Statement
Let’s start with the following Python list:
animals = ['lion', 'tiger', 'elephant']
Then write the first line of a if statement that verifies if the size of the animals list is great than 2:
if len(animals) > 2:
At this point we don’t add any other line to our code and we try to run this code.
$ python eof_if.py
File "eof_if.py", line 4
^
SyntaxError: unexpected EOF while parsing
We get back the error “unexpected EOF while parsing”.
The Python interpreter raises the unexpected EOF while parsing exception when using an if statement if the code inside the if condition is not present.
Now let’s do the following:
- Add a print statement inside the if condition.
- Specify an else condition immediately after that.
- Don’t write any code inside the else condition.
animals = ['lion', 'tiger', 'elephant']
if len(animals) > 2:
print("The animals list has more than two elements")
else:
When you run this code you get the following output.
$ python eof_if.py
File "eof_if.py", line 6
^
SyntaxError: unexpected EOF while parsing
This time the error is at line 6 that is the line immediately after the else statement.
The Python interpreter doesn’t like the fact that the Python file ends before the else block is complete.
That’s why to fix this error we add another print statement inside the else statement.
if len(animals) > 2:
print("The animals list has more than two elements")
else:
print("The animals list has less than two elements")
$ python eof_if.py
The animals list has more than two elements
The error doesn’t appear anymore and the execution of the Python program is correct.
Note: we are adding the print statements just as examples. You could add any lines you want inside the if and else statements to complete the expected structure for the if else statement.
Unexpected EOF While Parsing With Python Function
The error “unexpected EOF while parsing” occurs with Python functions when the body of the function is not provided.
To replicate this error write only the first line of a Python function called calculate_sum(). The function takes two parameters, x and y.
def calculate_sum(x,y):
At this point this is the only line of code in our program. Execute the program…
$ python eof_function.py
File "eof_function.py", line 4
^
SyntaxError: unexpected EOF while parsing
The EOF error again!
Let’s say we haven’t decided yet what the implementation of the function will be. Then we can simply specify the Python pass statement.
def calculate_sum(x,y):
pass
Execute the program, confirm that there is no output and that the Python interpreter doesn’t raise the exception anymore.
The exception “unexpected EOF while parsing” can occur with several types of Python loops: for loops but also while loops.
On the first line of your program define an integer called index with value 10.
Then write a while condition that gets executed as long as index is bigger than zero.
index = 10
while (index > 0):
There is something missing in our code…
…we haven’t specified any logic inside the while loop.
When you execute the code the Python interpreter raises an EOF SyntaxError because the while loop is missing its body.
$ python eof_while.py
File "eof_while.py", line 4
^
SyntaxError: unexpected EOF while parsing
Add two lines to the while loop. The two lines print the value of the index and then decrease the index by 1.
index = 10
while (index > 0):
print("The value of index is " + str(index))
index = index - 1
The output is correct and the EOF error has disappeared.
$ python eof_while.py
The value of index is 10
The value of index is 9
The value of index is 8
The value of index is 7
The value of index is 6
The value of index is 5
The value of index is 4
The value of index is 3
The value of index is 2
The value of index is 1
Unexpected EOF While Parsing Due to Missing Brackets
The error “unexpected EOF while parsing” can also occur when you miss brackets in a given line of code.
For example, let’s write a print statement:
print("Codefather"
As you can see I have forgotten the closing bracket at the end of the line.
Let’s see how the Python interpreter handles that…
$ python eof_brackets.py
File "eof_brackets.py", line 2
^
SyntaxError: unexpected EOF while parsing
It raises the SyntaxError that we have already seen multiple times in this tutorial.
Add the closing bracket at the end of the print statement and confirm that the code works as expected.
Unexpected EOF When Calling a Function With Incorrect Syntax
Now we will see what happens when we define a function correctly but we miss a bracket in the function call.
def print_message(message):
print(message)
print_message(
The definition of the function is correct but the function call was supposed to be like below:
print_message()
Instead we have missed the closing bracket of the function call and here is the result.
$ python eof_brackets.py
File "eof_brackets.py", line 6
^
SyntaxError: unexpected EOF while parsing
Add the closing bracket to the function call and confirm that the EOF error disappears.
Unexpected EOF While Parsing With Try Except
A scenario in which the unexpected EOF while parsing error can occur is when you use a try statement and you forget to add the except or finally statement.
Let’s call a function inside a try block without adding an except block and see what happens…
def print_message(message):
print(message)
try:
print_message()
When you execute this code the Python interpreter finds the end of the file before the end of the exception handling block (considering that except is missing).
$ python eof_try_except.py
File "eof_try_except.py", line 7
^
SyntaxError: unexpected EOF while parsing
The Python interpreter finds the error on line 7 that is the line immediately after the last one.
That’s because it expects to find a statement that completes the try block and instead it finds the end of the file.
To fix this error you can add an except or finally block.
try:
print_message()
except:
print("An exception occurred while running the function print_message()")
When you run this code you get the exception message because we haven’t passed an argument to the function. The print_message() function requires one argument to be passed.
Modify the function call as shown below and confirm that the code runs correctly:
print_message("Hello")
Conclusion
After going through this tutorial you have all you need to understand why the “unexpected EOF while parsing” error occurs in Python.
You have also learned how to find at which line the error occurs and what you have to do to fix it.
I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!