Ошибка при выполнении js вызова как исправить

Когда вы создали игру «Угадай номер» в предыдущей статье, вы, возможно, обнаружили, что она не работает. Не бойтесь — эта статья призвана избавить вас от разрыва волос над такими проблемами, предоставив вам несколько простых советов о том, как найти и исправить ошибки в программах JavaScript.
  • Назад
  • Обзор: Первые шаги
  • Далее

Когда вы создали игру «Угадай номер» в предыдущей статье, вы, возможно, обнаружили, что она не работает. Не бойтесь — эта статья призвана избавить вас от разрыва волос над такими проблемами, предоставив вам несколько простых советов о том, как найти и исправить ошибки в программах JavaScript.

Нужно: базовая компьютерная грамотность, базовое понимание HTML и CSS, понимание того, что такое JavaScript.
Цель получить способность и уверенность в том, чтобы приступить к исправлению простых проблем в вашем собственном коде.

Типы ошибок

Когда вы делаете что-то не так в коде, есть два основных типа ошибок, с которыми вы столкнётесь:

  • Синтаксические ошибки: Это орфографические ошибки в коде, которые фактически заставляют программу вообще не запускаться, или перестать работать на полпути — вам также будут предоставлены некоторые сообщения об ошибках. Обычно они подходят для исправления, если вы знакомы с правильными инструментами и знаете, что означают сообщения об ошибках!
  • Логические ошибки: Это ошибки, когда синтаксис действительно правильный, но код не тот, каким вы его предполагали, что означает, что программа работает успешно, но даёт неверные результаты. Их часто сложнее находить, чем синтаксические ошибки, так как обычно не возникает сообщение об ошибке, которое направляет вас к источнику ошибки.

Ладно, все не так просто — есть и другие отличия, которые вы поймёте, пока будете изучать язык JavaScript глубже. Однако вышеуказанной классификации достаточно на раннем этапе вашей карьеры. Мы рассмотрим оба эти типа в дальнейшем.

Ошибочный пример

Чтобы начать работу, давайте вернёмся к нашей игре с угадыванием чисел — за исключением того, что мы будем изучать версию с некоторыми преднамеренными ошибками. Перейдите в Github и сделайте себе локальную копию number-game-errors.html (см. здесь как это работает).

  1. Чтобы начать работу, откройте локальную копию внутри вашего любимого текстового редактора и вашего браузера.
  2. Попробуйте сыграть в игру — вы заметите, что когда вы нажимаете кнопку «Submit guess», она не работает!

Примечание: Возможно, у вас может быть собственная версия игрового примера, которая не работает, которую вы можете исправить! Мы по-прежнему хотели бы, чтобы вы работали над статьёй с нашей версией, чтобы вы могли изучать методы, которые мы здесь преподаём. Затем вы можете вернуться и попытаться исправить ваш пример.

На этом этапе давайте рассмотрим консоль разработчика, чтобы увидеть, можем ли мы видеть какие-либо синтаксические ошибки, а затем попытаемся их исправить. Вы узнаете, как это сделать, ниже.

Исправление синтаксических ошибок

Раньше в курсе мы заставили вас набрать некоторые простые команды JavaScript в консоль разработчика JavaScript (если вы не можете вспомнить, как открыть это в своём браузере, следуйте предыдущей ссылке, чтобы узнать, как это сделать). Что ещё более полезно, так это то, что консоль предоставляет вам сообщения об ошибках всякий раз, когда существует синтаксическая ошибка внутри JavaScript, которая подаётся в механизм JavaScript браузера. Теперь пойдём на охоту.

  1. Перейдите на вкладку, в которой у вас есть number-game-errors.html, и откройте консоль JavaScript. Вы должны увидеть сообщение об ошибке в следующих строках:
  2. Это довольно простая ошибка для отслеживания, и браузер даёт вам несколько полезных бит информации, которые помогут вам (скриншот выше от Firefox, но другие браузеры предоставляют аналогичную информацию). Слева направо, у нас есть:
    • Красный «x» означает, что это ошибка.
    • Сообщение об ошибке, указывающее, что пошло не так: «TypeError: guessSubmit.addeventListener не является функцией»
    • Ссылка «Узнать больше», которая ссылается на страницу MDN, которая объясняет, что эта ошибка означает в огромных количествах деталей.
    • Имя файла JavaScript, который ссылается на вкладку «Отладчик» консоли разработчика. Если вы перейдёте по этой ссылке, вы увидите точную строку, где подсвечивается ошибка.
    • Номер строки, в которой находится ошибка, и номер символа в этой строке, где первая ошибка. В этом случае у нас есть строка 86, символ номер 3.
  3. Если мы посмотрим на строку 86 в нашем редакторе кода, мы найдём эту строку:
    guessSubmit.addeventListener('click', checkGuess);
    
  4. В сообщении об ошибке говорится, что «guessSubmit.addeventListener не является функцией», поэтому мы, вероятно, где-то ошиблись. Если вы не уверены в правильности написания синтаксиса, часто бывает полезно найти функцию на MDN. Лучший способ сделать это в настоящее время — поиск «mdn имя-функции» в вашей любимой поисковой системе. Вот ссылка, которая поможет сократить вам некоторое время в данном случае: addEventListener().
  5. Итак, глядя на эту страницу, кажется, что ошибка в том, что мы неправильно назвали имя функции! Помните, что JavaScript чувствителен к регистру, поэтому любые незначительные отличия в орфографии или регистре текста могут вызвать ошибку. Изменение этого параметра в addEventListener должно быть исправлено. Сделайте это сейчас.

**Примечание:**См. наш TypeError: «x» не является справочной страницей функций для получения дополнительной информации об этой ошибке.

Синтаксические ошибки: второй раунд

Примечание: console.log() это часто используемая функция отладки, которая выводит значение в консоль. Поэтому она будет выводить значение lowOrHi в консоли, как только мы попытаемся установить его в строке 48.

  1. Сохраните и обновите страницу, и вы увидите, что ошибка исчезла.
  2. Теперь, если вы попробуете ввести значение и нажать кнопку «Submit guess», вы увидите … другую ошибку!
  3. На этот раз сообщается об ошибке: «TypeError: lowOrHi is null», в строке 78.

    Примечание: Null — это специальное значение, которое означает «ничего» или «не значение». Поэтому lowOrHi был объявлен и инициализирован без значения — у него нет типа или значения.

    Примечание: Эта ошибка не появилась, как только страница была загружена, потому что эта ошибка произошла внутри функции (внутри checkGuess() { ... } блока). Об этом вы узнаете более подробно в нашей более поздней статье о функциях, код внутри функций выполняется в отдельной области для кода внешних функций. В этом случае код не был запущен, и ошибка не была брошена до тех пор, пока функция checkGuess() не была запущена строкой 86.

  4. Посмотрите на строку 78, и вы увидите следующий код:
    lowOrHi.textContent = 'Last guess was too high!';
    
  5. Эта строка пытается установить свойство textContent переменной lowOrHi как текстовую строку, но это не работает, поскольку lowOrHi не содержит того, что должна. Давайте посмотрим, почему так происходит — попробуйте найти другие экземпляры lowOrHi в коде. Самый ранний экземпляр, который вы найдёте в JavaScript, находится в строке 48:
    const lowOrHi = document.querySelector('lowOrHi');
    
  6. На этом этапе мы пытаемся заставить переменную содержать ссылку на элемент документа HTML. Давайте проверим, является ли значение null после выполнения этой строки. Добавьте следующий код в строку 49:
  7. Сохраните и обновите, и вы должны увидеть результат работы console.log() в консоли браузера.
    Разумеется, значение lowOrHi на данный момент равно null, поэтому определённо существует проблема в строке 48.
  8. Давайте подумаем о том, что может быть проблемой. Строка 48 использует метод document.querySelector() для получения ссылки на элемент, выбирая его с помощью селектора CSS. Посмотрев далее наш файл, мы можем найти обсуждаемый элемент <p>:
  9. Поэтому нам нужен селектор классов, который начинается с точки (.), но селектор, передаваемый в метод querySelector() в строке 48, не имеет точки. Возможно, это и есть проблема! Попробуйте изменить lowOrHi на .lowOrHi в строке 48.
  10. Повторите попытку сохранения и обновления, и ваш вызов console.log() должен вернуть элемент <p>, который мы хотим. Уф! Ещё одна ошибка исправлена! Вы можете удалить строку с console.log() сейчас, или оставить для дальнейшего применения — выбирайте сами.

Примечание: Загляните на справочную страницу TypeError: «x» is (not) «y», чтобы узнать больше об этой ошибке.

Синтаксические ошибки: третий раунд

  1. Теперь, если вы снова попробуете сыграть в игру, вы должны добиться большего успеха — игра должна играть абсолютно нормально, пока вы не закончите игру, либо угадав нужное число, либо потеряв жизни.
  2. На данном этапе игра снова слетает, и выводится такая же ошибка, как и в начале — «TypeError: resetButton.addeventListener is not a function»! Однако, теперь она происходит из-за строки 94.
  3. Посмотрев на строку 94, легко видеть, что здесь сделана такая же ошибка. Нам просто нужно изменить addeventListener на addEventListener.

Логическая ошибка

На этом этапе игра должна проходить отлично, однако, поиграв несколько раз, вы, несомненно заметите, что случайное число, которое вы должны угадать, всегда 0 или 1. Определённо не совсем так, как мы хотим, чтобы игра была разыграна!

Безусловно, где-то в игре есть логическая ошибка — игра не возвращает ошибку, она просто работает неправильно.

  1. Найдём переменную randomNumber , и строку где в первый раз устанавливали случайное число. Пример, в котором мы храним случайное число, которое должны угадать, на строке 44:
    let randomNumber = Math.floor(Math.random()) + 1;
    

    И на строке 113, где мы генерируем случайное число, каждый раз после окончания игры:

    randomNumber = Math.floor(Math.random()) + 1;
    
  2. Чтобы проверить, действительно ли проблема в этом, давайте обратимся к нашему другу console.log() снова — вставьте её ниже строк с ошибками:
    console.log(randomNumber);
    
  3. Сохраните и обновите, а дальше попробуйте пару раз сыграть — в консоли вы увидите что randomNumber равна 1 в каждой точке, где вы её записали после строк с ошибками.

Работаем через логику

Чтобы исправить это, давайте рассмотрим как работает строка. Первое, мы вызываем Math.random(), который генерирует случайное десятичное число, между 0 и 1, например 0.5675493843.

Дальше, мы передаём результат вызова Math.random() через Math.floor(), который округляет число вниз, до ближайшего целого числа. Затем мы добавляем 1 к данному результату:

Math.floor(Math.random()) + 1;

Округление случайного десятичного числа к меньшему, всегда будет возвращать 0, так что добавление к нему единицы будет возвращать всегда 1. Нам нужно умножить случайное число на 100, прежде чем мы округлим его к меньшему. Следующая строка вернёт нам случайное число между 0 и 99:

Math.floor(Math.random() * 100);

поэтому нам нужно добавить 1, чтоб нам возвращалось случайное число между 1 и 100:

Math.floor(Math.random() * 100) + 1;

А теперь, исправьте обе строки с ошибками, затем сохраните и обновите, игра должна работать так, как мы и планировали!

Другие распространённые ошибки

Существуют и другие распространённые ошибки, которые вы обнаружите в своём коде. В этом разделе показано большинство из них.

SyntaxError: отсутствует ; перед постановкой

Эта ошибка обычно означает что вы упустили точку с запятой в конце одной из ваших строк кода, но иногда ошибка может быть более загадочной. Например, если мы изменим эту строку внутри функции checkGuess() :

var userGuess = Number(guessField.value);

на эту

var userGuess === Number(guessField.value);

Это вызовет данную ошибку, потому что браузер подумает, что вы пытались сделать что-то другое. Вы должны быть уверены, что вы не перепутали оператор присваивания (=), который присваивает значение переменной — с оператором сравнения (===), который строго сравнивает операнды, и возвращает true/false .

В программе всегда говорится, что вы выиграли, независимо от того, что вы ввели

Причиной этому является все то же перепутывание оператора присваивания (=) со строгим сравнением (===). Например, если мы изменим внутри checkGuess() эту строку кода:

if (userGuess === randomNumber) {

на эту

if (userGuess = randomNumber) {

мы всегда будем получать true, заставляя программу сообщать, что игра была выиграна. Будьте осторожны!

SyntaxError: отсутствует ) после списка аргументов

Эта ошибка проста — обычно она означает, что вы пропустили закрывающую скобку с конца вызова функции / метода.

SyntaxError: missing : after property id

Эта ошибка обычно связана с неправильно сформированным объектом JavaScript, но в этом случае нам удалось получить её, изменив

на

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

SyntaxError: missing } after function body

Это легко — обычно это означает, что вы пропустили одну из ваших фигурных скобок из функции или условной структуры. Мы получили эту ошибку, удалив одну из закрывающих фигурных скобок возле нижней части функции checkGuess().

SyntaxError: expected expression, got ‘string‘ or SyntaxError: unterminated string literal

Эти ошибки обычно означает, что вы пропустили открывающую или закрывающую кавычку для строковых значений. В первой ошибки выше, строка будет заменена на неожиданный персонаж (ей) , что браузер нашёл вместо кавычек в начале строки. Вторая ошибка означает , что строка не закончилась кавычки.

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

Резюме

Итак, мы научились основам выяснения ошибок в простых программах JavaScript. Не всегда так просто разобраться, что не так в вашем коде, но, по крайней мере, это сэкономит вам несколько часов сна и позволит вам продвигаться немного быстрее, когда что-либо заработает не так, как ожидалось, в вашем учебном путешествии.

Смотрите также

  • Есть много других типов ошибок, которые не перечислены здесь; мы составляем ссылку , которая объясняет , что они означают подробно — см. ссылку ошибки JavaScript .
  • Если вы столкнётесь с любыми ошибками в коде, которые вы не знаете , как исправить после прочтения этой статьи, вы можете получить помощь! Спросите на нить обучения Область дискурсе , или в #mdn IRC канал на Mozilla IRC. Расскажите нам, какая у вас ошибка, и мы постараемся вам помочь. Приложите пример своего кода для большей ясности проблемы.
  • Назад
  • Обзор: Первые шаги
  • Далее

Время прочтения
8 мин

Просмотры 11K

Всем привет! Вдохновленные успехом предыдущей статьи, которая была написана в преддверии запуска курса «Fullstack разработчик JavaScript«, мы решили продолжить серию статей для новичков и всех тех, кто только начинает заниматься программированием на языке JavaScript. Cегодня мы поговорим об ошибках, которые случаются в JS, а также о том, как именно с ними бороться.

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

Неизвестный тимлид

Типичные ошибки начинающих

Итак, начнем с самых примитивных ошибок. Допустим, вы только недавно закончили изучать основы HTML и CSS и теперь активно принялись за программирование на JavaScript. Для примера: вы хотите, чтобы при клике на кнопку у вас открывалось, к примеру, скрытое до этого момента модальное окно. Так же вы хотите, чтобы у вас по нажатию на крестик это окно закрывалось. Интерактивный пример доступен здесь (я выбрал bitbucket из-за того, что его интерфейс мне кажется самым простым, да и не все же на гитхабе сидеть).

	let modal_alert = document.querySelector(".modal_alert")
	let hero__btn = document.querySelector(".hero__btn")
	let modal_close = document.querySelector(".modal-close ")
	//мы выбрали из DOM модели наши элементы. К слову, я использую bulma для упрощения процесса верстки

	//теперь мы хотим провести над нашими элементами какие-то операции:

	hero__btn.addEventListener("click", function(){
    	modal_alert.classList.add("helper_visible");
	})

	modal_close.addEventListener("click", function(){
    	modal_alert.classList.remove("helper_visible");
	})
//если мы хотим увидеть форму, то просто вешаем доп. класс, в котором прописано css-свойство display:flex. И наоборот, если хотим скрыть.

В нашем index.html, кроме верстки, мы внутри тэга head вставляем наш script:

	<script src="code.js"></script>

В index.html кроме верстки внутри тэга head мы вставляем наш script:

	<script src="code.js"></script>

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

Что весьма печально, новички часто теряются и не понимают, что делать с красными строчками, словно это приговор какой-то, а не подсказка о том, что не так в вашей программе. Если перевести, то браузер говорит нам, что он не может прочитать свойство addEventListener нулевого значения. Значит, почему-то из DOM модели мы не получили наш элемент. Какой алгоритм действий нужно предпринять?

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

Что делать в таком случае? Просто добавьте атрибут defer внутрь вашего тэга скрипт (или async, но я не буду сейчас вдаваться в подробности их работы, это можно прочитать здесь ). Или можете просто переместить вниз ваш тэг script перед закрывающим body, это тоже сработает.

Во-вторых, проверьте опечатки. Изучите методологию БЭМ — она полезна ещё и тем, что вы хорошо знаете, как пишется ваш элемент — ведь пишите классы по единой логике, и стараетесь пользоваться только правильным английским языком. Или копируете сразу название элемента в JS файл.

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

Загадочная ошибка

Больше всего новичков вводит в ступор странная ошибка последней строчки кода. Приведем пример:

В консоли выводится что-то непонятное. Если переводить, то буквально это «Неожиданный конец ввода» — и что с этим делать? Кроме того, новичок по привычке смотрит на номер строки. На ней вроде все нормально. И почему тогда консоль на нее указывает?

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

	// тут у нас просто два массива с заголовками и статьями
	let root = document.getElementById("root"); // реактно подобно использую root
	let article__btn = document.querySelector("article__btn");
	// при клике на кнопку прочитаем статью
	
	article__btn.onclick = () => {
		for (let i = 0; i < headers.length; i++) {
			root.insertAdjacentHTML("beforeend", `
		<div class="content is-medium">
			<h1>${headers[i]} </h1>
			<p>${paragraps[i]}</p>
		</div>`)
		//изъятие фигурной скобки выполнено профессионалами. Не повторять на продакшене
	}

Теперь JavaScript не понимает, где у него конец тела функции, а где конец цикла и не может интерпретировать код.

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

Дробим код

Чаще всего стоит заниматься написанием кода, тестируя его работу небольшими кусочками.

Или как нормальный человек изучить TDD

К примеру, вам нужно простую программу, которая принимает данные на вход от пользователя, складывает их в массив и после этого выводит их средние значения:

	let input_number = prompt("Введите количество переменных");
	// определяем, какое количество переменных к нам придет
	let numbers = [];
	
	function toArray(input_number){
		for (let i = 0; i < input_number; i++) {
			let x = prompt(`Введите значение ${i}`);
			numbers.push(x); // и складываем значения в массив
		}
	}
	toArray(input_number); 
	
	function toAverage(numbers){
		let sum = 0;
		for (let i = 0; i < numbers.length; i++) {
			sum += numbers[i];
		}
		return sum/numbers.length;
	}
	alert(toAverage(numbers));

На первый неискушенный взгляд, в данном коде вполне все нормально. В нем есть основная логика, раздробленная на две функции, каждую из которой можно применять потом отдельно. Однако опытный программист сразу скажет, что это не заработает, ведь из prompt данные к нам приходят в виде строки. Причем JS (таков его толерантно-пофигистичный характер) нам все запустит, но на выходе выдаст настолько невероятную чепуху, что даже будет непросто понять, как мы дошли до жизни такой. Итак, давайте попробуем что-нибудь посчитать в нашем интерактивном примере. Введем допустим число 3 в количество переменных, и 1 2 3 в поле ввода данных:

Что? Чего? Ладно, это JavaScript. Поговорим лучше, как мы могли бы избежать такого странного вывода.

Надо было писать на Python, он бы по-человечески предупредил нас об ошибке

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

Вариант кода, в котором вероятность неожиданного вывода снижена:

	let input_number = prompt("Введите количество переменных");

	console.log(typeof(input_number));
	let numbers = [];
	
	function toArray(input_number){
		for (let i = 0; i < input_number; i++) {
			let x = prompt(`Введите значение ${i}`);
			numbers.push(x);
		}
	}

	toArray(input_number);
	console.log(numbers);
	
	function toAverage(numbers){
		let sum = 0;
		for (let i = 0; i < numbers.length; i++) {
			sum += numbers[i];
		}
		return sum/numbers.length;
	}
	console.log(typeof(toAverage(numbers)));
	alert(toAverage(numbers));

Иными словами, все подозрительные места, в которых что-то могло пойти не так, я вывел в консоль, чтобы убедиться, что все идет так, как я ожидаю. Конечно, данные console.log — детские игрушки и в норме, естественно, нужно изучить любую приличную библиотеку для тестирования. Например эту. Результат этой отладочной программы можно увидеть в инструментах разработчика здесь. Как починить, я думаю, вопросов не будет, но если если интересно, то вот (и да, это можно сделать просто двумя плюсами).

Шаг вперед: осваиваем Chrome Dev Tools

Дебаг с использованием console.log в 2019 — это уже несколько архаичная штука (но мы все равно ее никогда ее не забудем, она уже нам как родная). Каждый разработчик, который мечтает носить гордое звание профессионала, должен освоить богатый инструментарий современных средств разработки.

Попробуем починить проблемные места в нашем коде с помощью Dev Tools. Если нужна документация с примерами, всё можно прочитать вот здесь. А мы попробуем разобрать предыдущий пример с помощью Dev Tools.

Итак, открываем пример. У нас явно запрятался какой-то баг в коде, но как понять, в какой момент JavaScript начал что-то неправильно считать?

Правильно, оборачиваем эту радость тестами на тип переменной, это же очень просто

Идем во вкладку Sources в инструментах разработчика. Откройте файл code.js. У вас будут 3 части: первая слева, в которой отображается список файлов и вторая — в которой у нас отображается код. Но больше всего информации мы сможете почерпнуть из третьей части снизу, в которой отображается ход выполнения нашего кода. Давайте поставим breakpoint на 15 строчке (для этого надо щелкнуть по номеру строки в окне, где у нас отображается код, после чего у вас появится голубая метка). Перезапустите страницу, и введите любые значения в нашу программу.

Теперь вы можете вытащить из нижней панели debug массу полезной информации. Вы обнаружите, что JS не особенно задумываясь над типом переменных

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

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

Учимся перехватывать ошибки

Конструкция try… catch встречается во всех современных языках программирования. Зачем эта синтаксическая конструкция нужна практически? Дело в том, что при возникновении ошибки в коде, он останавливает свое выполнение на месте ошибки — и все, дальнейшие инструкции интерпретатор не исполнит. В реально работающем приложении, из нескольких сотен строчек кода, нас это не устроит. И предположим, что мы хотим перехватить код ошибки, передать разработчику ее код, и продолжить выполнение дальше.

Наша статья была бы неполной без краткого описания основных типов ошибки в JavaScript:

  • Error — общий конструктор объекта ошибки.
  • EvalError — тип ошибки, появляющийся во время ошибок исполнения eval(), но не синтаксических, а при неправильном использовании этой глобальной функции.
  • RangeError — происходит, когда вы выходите за пределы допустимого диапазона в исполнении вашего кода.
  • ReferenceError — происходит, когда вы пытаетесь вызвать переменную, функцию или объект, которых нет в программе.
  • SyntaxError — ошибка в синтаксисе.
  • TypeError — происходит при попытке создания объекта с неизвестным типом переменной или при попытке вызова несуществующего метода
  • URIError — редко встречающий код, который возникает при неправильном использовании методов encodeURL и DecodeURL.

Здорово, давайте теперь немного попрактикуемся и посмотрим на практике, где мы можем использовать конструкцию try… catch. Сам принцип работы данной конструкции совсем простой — интерпретатор пытается исполнить код внутри try, если получается — то все продолжается, словно этой конструкции никогда не было. А вот если произошла ошибка — мы ее перехватываем и можем обработать, к примеру, сказав пользователю, где именно он допустил промах.

Давайте создадим самый простой калькулятор (даже калькулятором его называть громко, я бы сказал:«исполнитель введенных выражений»). Его интерактивный пример можно найти здесь. Хорошо, давайте теперь посмотрим на наш код:

	let input = document.querySelector("#enter");
	let button = document.querySelector("#enter_button");
	let result_el = document.querySelector("#result ");
	
	button.onclick = () => {
		try {
			let result = eval(input.value); //пробуем, если все будет корректно, тогда catch не сработает
			result_el.innerHTML = result;
		} catch (error) {
			console.error(error.name);
			result_el.innerHTML = "Вы что-то не то ввели, молодой человек<br> Подумайте еще раз";
			//можно пользователю объяснять, что он не прав, если он допустил ошибку
			//хотя естественно пользователю лучше не давать эту возможность))
		}
	}
 

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

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

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

И по традиции, полезные ссылочки:

  • Пишем собственный фреймворк для тестирования. Полезно для общего понимания стратегии тестирования.
  • Полная документация по ошибкам, в том числе и экспериментальные фичи
  • Невероятно полезная статья на MDN, которая описывает большинство проблем, которые возникают в начале разработки на JS: отладку, полифиллы, дебагер и многое другое

На этом все. Ждем ваши комментарии и приглашаем на бесплатный вебинар, где поговорим о возможностях фреймворка SvelteJS.

Murphy’s law states that whatever can go wrong will eventually go wrong. This applies a tad too well in the world of programming. If you create an application, chances are you’ll create bugs and other issues. Errors in JavaScript are one such common issue!

A software product’s success depends on how well its creators can resolve these issues before hurting their users. And JavaScript, out of all programming languages, is notorious for its average error handling design.

If you’re building a JavaScript application, there’s a high chance you’ll mess up with data types at one point or another. If not that, then you might end up replacing an undefined with a null or a triple equals operator (===) with a double equals operator (==).

It’s only human to make mistakes. This is why we will show you everything you need to know about handling errors in JavaScript.

This article will guide you through the basic errors in JavaScript and explain the various errors you might encounter. You’ll then learn how to identify and fix these errors. There are also a couple of tips to handle errors effectively in production environments.

Without further ado, let’s begin!

Check Out Our Video Guide to Handling JavaScript Errors

What Are JavaScript Errors?

Errors in programming refer to situations that don’t let a program function normally. It can happen when a program doesn’t know how to handle the job at hand, such as when trying to open a non-existent file or reaching out to a web-based API endpoint while there’s no network connectivity.

These situations push the program to throw errors to the user, stating that it doesn’t know how to proceed. The program collects as much information as possible about the error and then reports that it can not move ahead.

Murphy’s law states that whatever can go wrong will eventually go wrong 😬 This applies a bit too well in the world of JavaScript 😅 Get prepped with this guide 👇Click to Tweet

Intelligent programmers try to predict and cover these scenarios so that the user doesn’t have to figure out a technical error message like “404” independently. Instead, they show a much more understandable message: “The page could not be found.”

Errors in JavaScript are objects shown whenever a programming error occurs. These objects contain ample information about the type of the error, the statement that caused the error, and the stack trace when the error occurred. JavaScript also allows programmers to create custom errors to provide extra information when debugging issues.

Properties of an Error

Now that the definition of a JavaScript error is clear, it’s time to dive into the details.

Errors in JavaScript carry certain standard and custom properties that help understand the cause and effects of the error. By default, errors in JavaScript contain three properties:

  1. message: A string value that carries the error message
  2. name: The type of error that occurred (We’ll dive deep into this in the next section)
  3. stack: The stack trace of the code executed when the error occurred.

Additionally, errors can also carry properties like columnNumber, lineNumber, fileName, etc., to describe the error better. However, these properties are not standard and may or may not be present in every error object generated from your JavaScript application.

Understanding Stack Trace

A stack trace is the list of method calls a program was in when an event such as an exception or a warning occurs. This is what a sample stack trace accompanied by an exception looks like:

The error “TypeError: Numeric argument is expected” is shown on a gray background with additional stack details.

Example of a Stack Trace.

As you can see, it starts by printing the error name and message, followed by a list of methods that were being called. Each method call states the location of its source code and the line at which it was invoked. You can use this data to navigate through your codebase and identify which piece of code is causing the error.

This list of methods is arranged in a stacked fashion. It shows where your exception was first thrown and how it propagated through the stacked method calls. Implementing a catch for the exception will not let it propagate up through the stack and crash your program. However, you might want to leave fatal errors uncaught to crash the program in some scenarios intentionally.

Errors vs Exceptions

Most people usually consider errors and exceptions as the same thing. However, it’s essential to note a slight yet fundamental difference between them.

To understand this better, let’s take a quick example. Here is how you can define an error in JavaScript:

const wrongTypeError = TypeError("Wrong type found, expected character")

And this is how the wrongTypeError object becomes an exception:

throw wrongTypeError

However, most people tend to use the shorthand form which defines error objects while throwing them:

throw TypeError("Wrong type found, expected character")

This is standard practice. However, it’s one of the reasons why developers tend to mix up exceptions and errors. Therefore, knowing the fundamentals is vital even though you use shorthands to get your work done quickly.

Types of Errors in JavaScript

There’s a range of predefined error types in JavaScript. They are automatically chosen and defined by the JavaScript runtime whenever the programmer doesn’t explicitly handle errors in the application.

This section will walk you through some of the most common types of errors in JavaScript and understand when and why they occur.

RangeError

A RangeError is thrown when a variable is set with a value outside its legal values range. It usually occurs when passing a value as an argument to a function, and the given value doesn’t lie in the range of the function’s parameters. It can sometimes get tricky to fix when using poorly documented third-party libraries since you need to know the range of possible values for the arguments to pass in the correct value.

Some of the common scenarios in which RangeError occurs are:

  • Trying to create an array of illegal lengths via the Array constructor.
  • Passing bad values to numeric methods like toExponential(), toPrecision(), toFixed(), etc.
  • Passing illegal values to string functions like normalize().

ReferenceError

A ReferenceError occurs when something is wrong with a variable’s reference in your code. You might have forgotten to define a value for the variable before using it, or you might be trying to use an inaccessible variable in your code. In any case, going through the stack trace provides ample information to find and fix the variable reference that is at fault.

Some of the common reasons why ReferenceErrors occur are:

  • Making a typo in a variable name.
  • Trying to access block-scoped variables outside of their scopes.
  • Referencing a global variable from an external library (like $ from jQuery) before it’s loaded.

SyntaxError

These errors are one of the simplest to fix since they indicate an error in the syntax of the code. Since JavaScript is a scripting language that is interpreted rather than compiled, these are thrown when the app executes the script that contains the error. In the case of compiled languages, such errors are identified during compilation. Thus, the app binaries are not created until these are fixed.

Some of the common reasons why SyntaxErrors might occur are:

  • Missing inverted commas
  • Missing closing parentheses
  • Improper alignment of curly braces or other characters

It’s a good practice to use a linting tool in your IDE to identify such errors for you before they hit the browser.

TypeError

TypeError is one of the most common errors in JavaScript apps. This error is created when some value doesn’t turn out to be of a particular expected type. Some of the common cases when it occurs are:

  • Invoking objects that are not methods.
  • Attempting to access properties of null or undefined objects
  • Treating a string as a number or vice versa

There are a lot more possibilities where a TypeError can occur. We’ll look at some famous instances later and learn how to fix them.

InternalError

The InternalError type is used when an exception occurs in the JavaScript runtime engine. It may or may not indicate an issue with your code.

More often than not, InternalError occurs in two scenarios only:

  • When a patch or an update to the JavaScript runtime carries a bug that throws exceptions (this happens very rarely)
  • When your code contains entities that are too large for the JavaScript engine (e.g. too many switch cases, too large array initializers, too much recursion)

The most appropriate approach to solve this error is to identify the cause via the error message and restructure your app logic, if possible, to eliminate the sudden spike of workload on the JavaScript engine.

URIError

URIError occurs when a global URI handling function such as decodeURIComponent is used illegally. It usually indicates that the parameter passed to the method call did not conform to URI standards and thus was not parsed by the method properly.

Diagnosing these errors is usually easy since you only need to examine the arguments for malformation.

EvalError

An EvalError occurs when an error occurs with an eval() function call. The eval() function is used to execute JavaScript code stored in strings. However, since using the eval() function is highly discouraged due to security issues and the current ECMAScript specifications don’t throw the EvalError class anymore, this error type exists simply to maintain backward compatibility with legacy JavaScript code.

If you’re working on an older version of JavaScript, you might encounter this error. In any case, it’s best to investigate the code executed in the eval() function call for any exceptions.

Creating Custom Error Types

While JavaScript offers an adequate list of error type classes to cover for most scenarios, you can always create a new error type if the list doesn’t satisfy your requirements. The foundation of this flexibility lies in the fact that JavaScript allows you to throw anything literally with the throw command.

So, technically, these statements are entirely legal:

throw 8
throw "An error occurred"

However, throwing a primitive data type doesn’t provide details about the error, such as its type, name, or the accompanying stack trace. To fix this and standardize the error handling process, the Error class has been provided. It’s also discouraged to use primitive data types while throwing exceptions.

You can extend the Error class to create your custom error class. Here is a basic example of how you can do this:

class ValidationError extends Error {
    constructor(message) {
        super(message);
        this.name = "ValidationError";
    }
}

And you can use it in the following way:

throw ValidationError("Property not found: name")

And you can then identify it using the instanceof keyword:

try {
    validateForm() // code that throws a ValidationError
} catch (e) {
    if (e instanceof ValidationError)
    // do something
    else
    // do something else
}

Top 10 Most Common Errors in JavaScript

Now that you understand the common error types and how to create your custom ones, it’s time to look at some of the most common errors you’ll face when writing JavaScript code.

Check Out Our Video Guide to The Most Common JavaScript Errors

1. Uncaught RangeError

This error occurs in Google Chrome under a few various scenarios. First, it can happen if you call a recursive function and it doesn’t terminate. You can check this out yourself in the Chrome Developer Console:

The error “Uncaught RangeError: Maximum call stack size exceeded” is shown on a red background beside a red cross icon with a recursive function’s code above it.

RangeError example with a recursive function call.

So to solve such an error, make sure to define the border cases of your recursive function correctly. Another reason why this error happens is if you have passed a value that is out of a function’s parameter’s range. Here’s an example:

The error “Uncaught RangeError: toExponential() argument must be between 0 and 100” is shown on a red background beside a red cross icon with a toExponential() function call above it.

RangeError example with toExponential() call.

The error message will usually indicate what is wrong with your code. Once you make the changes, it will be resolved.

num = 4. num.toExponential(2). Output: 4.00e+0.

Output for the toExponential() function call.

2. Uncaught TypeError: Cannot set property

This error occurs when you set a property on an undefined reference. You can reproduce the issue with this code:

var list
list.count = 0

Here’s the output that you’ll receive:

The error “Uncaught TypeError: Cannot set properties of undefined” is shown on a red background beside a red cross icon with a list.count = 0 assignment above it.

TypeError example.

To fix this error, initialize the reference with a value before accessing its properties. Here’s how it looks when fixed:

Setting list.count = 10 after initializing list with {} due to which the output is 10.

How to fix TypeError.

3. Uncaught TypeError: Cannot read property

This is one of the most frequently occurring errors in JavaScript. This error occurs when you attempt to read a property or call a function on an undefined object. You can reproduce it very easily by running the following code in a Chrome Developer console:

var func
func.call()

Here’s the output:

The error “Uncaught TypeError: Cannot read properties of undefined” is shown on a red background beside a red cross icon with func.call() above it.

TypeError example with undefined function.

An undefined object is one of the many possible causes of this error. Another prominent cause of this issue can be an improper initialization of the state while rendering the UI. Here’s a real-world example from a React application:

import React, { useState, useEffect } from "react";

const CardsList = () => {

    const [state, setState] = useState();

    useEffect(() => {
        setTimeout(() => setState({ items: ["Card 1", "Card 2"] }), 2000);
    }, []);

    return (
        <>
            {state.items.map((item) => (
                <li key={item}>{item}</li>
            ))}
        </>
    );
};

export default CardsList;

The app starts with an empty state container and is provided with some items after a delay of 2 seconds. The delay is put in place to imitate a network call. Even if your network is super fast, you’ll still face a minor delay due to which the component will render at least once. If you try to run this app, you’ll receive the following error:

The error “undefined is not an object” is shown on a grey background.

TypeError stack trace in a browser.

This is because, at the time of rendering, the state container is undefined; thus, there exists no property items on it. Fixing this error is easy. You just need to provide an initial default value to the state container.

// ...
const [state, setState] = useState({items: []});
// ...

Now, after the set delay, your app will show a similar output:

A bulleted list with two items reading "Card 1" and "Card 2".

Code output.

The exact fix in your code might be different, but the essence here is to always initialize your variables properly before using them.

4. TypeError: ‘undefined’ is not an object

This error occurs in Safari when you try to access the properties of or call a method on an undefined object. You can run the same code from above to reproduce the error yourself.

The error “TypeError: undefined is not an object” shown on a red background beside a red exclamation point icon with func.call() method call above it.

TypeError example with undefined function.

The solution to this error is also the same — make sure that you have initialized your variables correctly and they are not undefined when a property or method is accessed.

5. TypeError: null is not an object

This is, again, similar to the previous error. It occurs on Safari, and the only difference between the two errors is that this one is thrown when the object whose property or method is being accessed is null instead of undefined. You can reproduce this by running the following piece of code:

var func = null

func.call()

Here’s the output that you’ll receive:

The "TypeError: null is not an object" error message, shown on a red background beside a red exclamation point icon.

TypeError example with null function.

Since null is a value explicitly set to a variable and not assigned automatically by JavaScript. This error can occur only if you’re trying to access a variable you set null by yourself. So, you need to revisit your code and check if the logic that you wrote is correct or not.

6. TypeError: Cannot read property ‘length’

This error occurs in Chrome when you try to read the length of a null or undefined object. The cause of this issue is similar to the previous issues, but it occurs quite frequently while handling lists; hence it deserves a special mention. Here’s how you can reproduce the problem:

The error “Uncaught TypeError: Cannot read property 'length' of undefined” shown on a red background beside a red cross icon with myButton.length call above it.

TypeError example with an undefined object.

However, in the newer versions of Chrome, this error is reported as Uncaught TypeError: Cannot read properties of undefined. This is how it looks now:

The error “Uncaught TypeError: Cannot read properties of undefined” shown on a red background beside a red cross icon with myButton.length call above it.

TypeError example with an undefined object on newer Chrome versions.

The fix, again, is to ensure that the object whose length you’re trying to access exists and is not set to null.

7. TypeError: ‘undefined’ is not a function

This error occurs when you try to invoke a method that doesn’t exist in your script, or it does but can not be referenced in the calling context. This error usually occurs in Google Chrome, and you can solve it by checking the line of code throwing the error. If you find a typo, fix it and check if it solves your issue.

If you have used the self-referencing keyword this in your code, this error might arise if this is not appropriately bound to your context. Consider the following code:

function showAlert() {
    alert("message here")
}

document.addEventListener("click", () => {
    this.showAlert();
})

If you execute the above code, it will throw the error we discussed. It happens because the anonymous function passed as the event listener is being executed in the context of the document.

In contrast, the function showAlert is defined in the context of the window.

To solve this, you must pass the proper reference to the function by binding it with the bind() method:

document.addEventListener("click", this.showAlert.bind(this))

8. ReferenceError: event is not defined

This error occurs when you try to access a reference not defined in the calling scope. This usually happens when handling events since they often provide you with a reference called event in the callback function. This error can occur if you forget to define the event argument in your function’s parameters or misspell it.

This error might not occur in Internet Explorer or Google Chrome (as IE offers a global event variable and Chrome attaches the event variable automatically to the handler), but it can occur in Firefox. So it’s advisable to keep an eye out for such small mistakes.

9. TypeError: Assignment to constant variable

This is an error that arises out of carelessness. If you try to assign a new value to a constant variable, you’ll be met with such a result:

The error “Uncaught TypeError: Assignment to constant variable” shown on a red background beside a red cross icon with func = 6 assignment above it.

TypeError example with constant object assignment.

While it seems easy to fix right now, imagine hundreds of such variable declarations and one of them mistakenly defined as const instead of let! Unlike other scripting languages like PHP, there’s minimal difference between the style of declaring constants and variables in JavaScript. Therefore it’s advisable to check your declarations first of all when you face this error. You could also run into this error if you forget that the said reference is a constant and use it as a variable. This indicates either carelessness or a flaw in your app’s logic. Make sure to check this when trying to fix this issue.

10. (unknown): Script error

A script error occurs when a third-party script sends an error to your browser. This error is followed by (unknown) because the third-party script belongs to a different domain than your app. The browser hides other details to prevent leaking sensitive information from the third-party script.

You can not resolve this error without knowing the complete details. Here’s what you can do to get more information about the error:

  1. Add the crossorigin attribute in the script tag.
  2. Set the correct Access-Control-Allow-Origin header on the server hosting the script.
  3. [Optional] If you don’t have access to the server hosting the script, you can consider using a proxy to relay your request to the server and back to the client with the correct headers.

Once you can access the details of the error, you can then set down to fix the issue, which will probably be with either the third-party library or the network.

How to Identify and Prevent Errors in JavaScript

While the errors discussed above are the most common and frequent in JavaScript, you’ll come across, relying on a few examples can never be enough. It’s vital to understand how to detect and prevent any type of error in a JavaScript application while developing it. Here is how you can handle errors in JavaScript.

Manually Throw and Catch Errors

The most fundamental way of handling errors that have been thrown either manually or by the runtime is to catch them. Like most other languages, JavaScript offers a set of keywords to handle errors. It’s essential to know each of them in-depth before you set down to handle errors in your JavaScript app.

throw

The first and most basic keyword of the set is throw. As evident, the throw keyword is used to throw errors to create exceptions in the JavaScript runtime manually. We have already discussed this earlier in the piece, and here’s the gist of this keyword’s significance:

  • You can throw anything, including numbers, strings, and Error objects.
  • However, it’s not advisable to throw primitive data types such as strings and numbers since they don’t carry debug information about the errors.
  • Example: throw TypeError("Please provide a string")

try

The try keyword is used to indicate that a block of code might throw an exception. Its syntax is:

try {
    // error-prone code here
}

It’s important to note that a catch block must always follow the try block to handle errors effectively.

catch

The catch keyword is used to create a catch block. This block of code is responsible for handling the errors that the trailing try block catches. Here is its syntax:

catch (exception) {
    // code to handle the exception here
}

And this is how you implement the try and the catch blocks together:

try {
    // business logic code
} catch (exception) {
    // error handling code
}

Unlike C++ or Java, you can not append multiple catch blocks to a try block in JavaScript. This means that you can not do this:

try {
    // business logic code
} catch (exception) {
    if (exception instanceof TypeError) {
        // do something
    }
} catch (exception) {
    if (exception instanceof RangeError) {
    // do something
    }
}

Instead, you can use an if...else statement or a switch case statement inside the single catch block to handle all possible error cases. It would look like this:

try {
    // business logic code
} catch (exception) {
    if (exception instanceof TypeError) {
        // do something
    } else if (exception instanceof RangeError) {
        // do something else
    }
}

finally

The finally keyword is used to define a code block that is run after an error has been handled. This block is executed after the try and the catch blocks.

Also, the finally block will be executed regardless of the result of the other two blocks. This means that even if the catch block cannot handle the error entirely or an error is thrown in the catch block, the interpreter will execute the code in the finally block before the program crashes.

To be considered valid, the try block in JavaScript needs to be followed by either a catch or a finally block. Without any of those, the interpreter will raise a SyntaxError. Therefore, make sure to follow your try blocks with at least either of them when handling errors.

Handle Errors Globally With the onerror() Method

The onerror() method is available to all HTML elements for handling any errors that may occur with them. For instance, if an img tag cannot find the image whose URL is specified, it fires its onerror method to allow the user to handle the error.

Typically, you would provide another image URL in the onerror call for the img tag to fall back to. This is how you can do that via JavaScript:

const image = document.querySelector("img")

image.onerror = (event) => {
    console.log("Error occurred: " + event)
}

However, you can use this feature to create a global error handling mechanism for your app. Here’s how you can do it:

window.onerror = (event) => {
    console.log("Error occurred: " + event)
}

With this event handler, you can get rid of the multiple try...catch blocks lying around in your code and centralize your app’s error handling similar to event handling. You can attach multiple error handlers to the window to maintain the Single Responsibility Principle from the SOLID design principles. The interpreter will cycle through all handlers until it reaches the appropriate one.

Pass Errors via Callbacks

While simple and linear functions allow error handling to remain simple, callbacks can complicate the affair.

Consider the following piece of code:

const calculateCube = (number, callback) => {
    setTimeout(() => {
        const cube = number * number * number
        callback(cube)
    }, 1000)
}

const callback = result => console.log(result)

calculateCube(4, callback)

The above function demonstrates an asynchronous condition in which a function takes some time to process operations and returns the result later with the help of a callback.

If you try to enter a string instead of 4 in the function call, you’ll get NaN as a result.

This needs to be handled properly. Here’s how:

const calculateCube = (number, callback) => {

    setTimeout(() => {
        if (typeof number !== "number")
            throw new Error("Numeric argument is expected")

        const cube = number * number * number
        callback(cube)
    }, 1000)
}

const callback = result => console.log(result)

try {
    calculateCube(4, callback)
} catch (e) { console.log(e) }

This should solve the problem ideally. However, if you try passing a string to the function call, you’ll receive this:

The error “Uncaught Error: Numeric argument is expected” shown on a dark red background beside a red cross icon.

Error example with the wrong argument.

Even though you have implemented a try-catch block while calling the function, it still says the error is uncaught. The error is thrown after the catch block has been executed due to the timeout delay.

This can occur quickly in network calls, where unexpected delays creep in. You need to cover such cases while developing your app.

Here’s how you can handle errors properly in callbacks:

const calculateCube = (number, callback) => {

    setTimeout(() => {
        if (typeof number !== "number") {
            callback(new TypeError("Numeric argument is expected"))
            return
        }
        const cube = number * number * number
        callback(null, cube)
    }, 2000)
}

const callback = (error, result) => {
    if (error !== null) {
        console.log(error)
        return
    }
    console.log(result)
}

try {
    calculateCube('hey', callback)
} catch (e) {
    console.log(e)
}

Now, the output at the console will be:

The message “TypeError: Numeric argument is expected” shown on a dark grey background.

TypeError example with illegal argument.

This indicates that the error has been appropriately handled.

Handle Errors in Promises

Most people tend to prefer promises for handling asynchronous activities. Promises have another advantage — a rejected promise doesn’t terminate your script. However, you still need to implement a catch block to handle errors in promises. To understand this better, let’s rewrite the calculateCube() function using Promises:

const delay = ms => new Promise(res => setTimeout(res, ms));

const calculateCube = async (number) => {
    if (typeof number !== "number")
        throw Error("Numeric argument is expected")
    await delay(5000)
    const cube = number * number * number
    return cube
}

try {
    calculateCube(4).then(r => console.log(r))
} catch (e) { console.log(e) }

The timeout from the previous code has been isolated into the delay function for understanding. If you try to enter a string instead of 4, the output that you get will be similar to this:

The error “Uncaught (in promise) Error: Numeric argument is expected” shown on a dark grey background beside a red cross icon.

TypeError example with an illegal argument in Promise.

Again, this is due to the Promise throwing the error after everything else has completed execution. The solution to this issue is simple. Simply add a catch() call to the promise chain like this:

calculateCube("hey")
.then(r => console.log(r))
.catch(e => console.log(e))

Now the output will be:

The message “Error: Numeric argument is expected” shown on a dark grey background.

Handled TypeError example with illegal argument.

You can observe how easy it is to handle errors with promises. Additionally, you can chain a finally() block and the promise call to add code that will run after error handling has been completed.

Alternatively, you can also handle errors in promises using the traditional try-catch-finally technique. Here’s how your promise call would look like in that case:

try {
    let result = await calculateCube("hey")
    console.log(result)
} catch (e) {
    console.log(e)
} finally {
    console.log('Finally executed")
}

However, this works inside an asynchronous function only. Therefore the most preferred way to handle errors in promises is to chain catch and finally to the promise call.

throw/catch vs onerror() vs Callbacks vs Promises: Which is the Best?

With four methods at your disposal, you must know how to choose the most appropriate in any given use case. Here’s how you can decide for yourselves:

throw/catch

You will be using this method most of the time. Make sure to implement conditions for all possible errors inside your catch block, and remember to include a finally block if you need to run some memory clean-up routines after the try block.

However, too many try/catch blocks can make your code difficult to maintain. If you find yourself in such a situation, you might want to handle errors via the global handler or the promise method.

When deciding between asynchronous try/catch blocks and promise’s catch(), it’s advisable to go with the async try/catch blocks since they will make your code linear and easy to debug.

onerror()

It’s best to use the onerror() method when you know that your app has to handle many errors, and they can be well-scattered throughout the codebase. The onerror method enables you to handle errors as if they were just another event handled by your application. You can define multiple error handlers and attach them to your app’s window on the initial rendering.

However, you must also remember that the onerror() method can be unnecessarily challenging to set up in smaller projects with a lesser scope of error. If you’re sure that your app will not throw too many errors, the traditional throw/catch method will work best for you.

Callbacks and Promises

Error handling in callbacks and promises differs due to their code design and structure. However, if you choose between these two before you have written your code, it would be best to go with promises.

This is because promises have an inbuilt construct for chaining a catch() and a finally() block to handle errors easily. This method is easier and cleaner than defining additional arguments/reusing existing arguments to handle errors.

Keep Track of Changes With Git Repositories

Many errors often arise due to manual mistakes in the codebase. While developing or debugging your code, you might end up making unnecessary changes that may cause new errors to appear in your codebase. Automated testing is a great way to keep your code in check after every change. However, it can only tell you if something’s wrong. If you don’t take frequent backups of your code, you’ll end up wasting time trying to fix a function or a script that was working just fine before.

This is where git plays its role. With a proper commit strategy, you can use your git history as a backup system to view your code as it evolved through the development. You can easily browse through your older commits and find out the version of the function working fine before but throwing errors after an unrelated change.

You can then restore the old code or compare the two versions to determine what went wrong. Modern web development tools like GitHub Desktop or GitKraken help you to visualize these changes side by side and figure out the mistakes quickly.

A habit that can help you make fewer errors is running code reviews whenever you make a significant change to your code. If you’re working in a team, you can create a pull request and have a team member review it thoroughly. This will help you use a second pair of eyes to spot out any errors that might have slipped by you.

Best Practices for Handling Errors in JavaScript

The above-mentioned methods are adequate to help you design a robust error handling approach for your next JavaScript application. However, it would be best to keep a few things in mind while implementing them to get the best out of your error-proofing. Here are some tips to help you.

1. Use Custom Errors When Handling Operational Exceptions

We introduced custom errors early in this guide to give you an idea of how to customize the error handling to your application’s unique case. It’s advisable to use custom errors wherever possible instead of the generic Error class as it provides more contextual information to the calling environment about the error.

On top of that, custom errors allow you to moderate how an error is displayed to the calling environment. This means that you can choose to hide specific details or display additional information about the error as and when you wish.

You can go so far as to format the error contents according to your needs. This gives you better control over how the error is interpreted and handled.

2. Do Not Swallow Any Exceptions

Even the most senior developers often make a rookie mistake — consuming exceptions levels deep down in their code.

You might come across situations where you have a piece of code that is optional to run. If it works, great; if it doesn’t, you don’t need to do anything about it.

In these cases, it’s often tempting to put this code in a try block and attach an empty catch block to it. However, by doing this, you’ll leave that piece of code open to causing any kind of error and getting away with it. This can become dangerous if you have a large codebase and many instances of such poor error management constructs.

The best way to handle exceptions is to determine a level on which all of them will be dealt and raise them until there. This level can be a controller (in an MVC architecture app) or a middleware (in a traditional server-oriented app).

This way, you’ll get to know where you can find all the errors occurring in your app and choose how to resolve them, even if it means not doing anything about them.

3. Use a Centralized Strategy for Logs and Error Alerts

Logging an error is often an integral part of handling it. Those who fail to develop a centralized strategy for logging errors may miss out on valuable information about their app’s usage.

An app’s event logs can help you figure out crucial data about errors and help to debug them quickly. If you have proper alerting mechanisms set up in your app, you can know when an error occurs in your app before it reaches a large section of your user base.

It’s advisable to use a pre-built logger or create one to suit your needs. You can configure this logger to handle errors based on their levels (warning, debug, info, etc.), and some loggers even go so far as to send logs to remote logging servers immediately. This way, you can watch how your application’s logic performs with active users.

4. Notify Users About Errors Appropriately

Another good point to keep in mind while defining your error handling strategy is to keep the user in mind.

All errors that interfere with the normal functioning of your app must present a visible alert to the user to notify them that something went wrong so the user can try to work out a solution. If you know a quick fix for the error, such as retrying an operation or logging out and logging back in, make sure to mention it in the alert to help fix the user experience in real-time.

In the case of errors that don’t cause any interference with the everyday user experience, you can consider suppressing the alert and logging the error to a remote server for resolving later.

5. Implement a Middleware (Node.js)

The Node.js environment supports middlewares to add functionalities to server applications. You can use this feature to create an error-handling middleware for your server.

The most significant benefit of using middleware is that all of your errors are handled centrally in one place. You can choose to enable/disable this setup for testing purposes easily.

Here’s how you can create a basic middleware:

const logError = err => {
    console.log("ERROR: " + String(err))
}

const errorLoggerMiddleware = (err, req, res, next) => {
    logError(err)
    next(err)
}

const returnErrorMiddleware = (err, req, res, next) => {
    res.status(err.statusCode || 500)
       .send(err.message)
}

module.exports = {
    logError,
    errorLoggerMiddleware,
    returnErrorMiddleware
}

You can then use this middleware in your app like this:

const { errorLoggerMiddleware, returnErrorMiddleware } = require('./errorMiddleware')

app.use(errorLoggerMiddleware)

app.use(returnErrorMiddleware)

You can now define custom logic inside the middleware to handle errors appropriately. You don’t need to worry about implementing individual error handling constructs throughout your codebase anymore.

6. Restart Your App To Handle Programmer Errors (Node.js)

When Node.js apps encounter programmer errors, they might not necessarily throw an exception and try to close the app. Such errors can include issues arising from programmer mistakes, like high CPU consumption, memory bloating, or memory leaks. The best way to handle these is to gracefully restart the app by crashing it via the Node.js cluster mode or a unique tool like PM2. This can ensure that the app doesn’t crash upon user action, presenting a terrible user experience.

7. Catch All Uncaught Exceptions (Node.js)

You can never be sure that you have covered every possible error that can occur in your app. Therefore, it’s essential to implement a fallback strategy to catch all uncaught exceptions from your app.

Here’s how you can do that:

process.on('uncaughtException', error => {
    console.log("ERROR: " + String(error))
    // other handling mechanisms
})

You can also identify if the error that occurred is a standard exception or a custom operational error. Based on the result, you can exit the process and restart it to avoid unexpected behavior.

8. Catch All Unhandled Promise Rejections (Node.js)

Similar to how you can never cover for all possible exceptions, there’s a high chance that you might miss out on handling all possible promise rejections. However, unlike exceptions, promise rejections don’t throw errors.

So, an important promise that was rejected might slip by as a warning and leave your app open to the possibility of running into unexpected behavior. Therefore, it’s crucial to implement a fallback mechanism for handling promise rejection.

Here’s how you can do that:

const promiseRejectionCallback = error => {
    console.log("PROMISE REJECTED: " + String(error))
}

process.on('unhandledRejection', callback)

If you create an application, there are chances that you’ll create bugs and other issues in it as well. 😅 Learn how to handle them with help from this guide ⬇️Click to Tweet

Summary

Like any other programming language, errors are quite frequent and natural in JavaScript. In some cases, you might even need to throw errors intentionally to indicate the correct response to your users. Hence, understanding their anatomy and types is very crucial.

Moreover, you need to be equipped with the right tools and techniques to identify and prevent errors from taking down your application.

In most cases, a solid strategy to handle errors with careful execution is enough for all types of JavaScript applications.

Are there any other JavaScript errors that you still haven’t been able to resolve? Any techniques for handling JS errors constructively? Let us know in the comments below!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Murphy’s law states that whatever can go wrong will eventually go wrong. This applies a tad too well in the world of programming. If you create an application, chances are you’ll create bugs and other issues. Errors in JavaScript are one such common issue!

A software product’s success depends on how well its creators can resolve these issues before hurting their users. And JavaScript, out of all programming languages, is notorious for its average error handling design.

If you’re building a JavaScript application, there’s a high chance you’ll mess up with data types at one point or another. If not that, then you might end up replacing an undefined with a null or a triple equals operator (===) with a double equals operator (==).

It’s only human to make mistakes. This is why we will show you everything you need to know about handling errors in JavaScript.

This article will guide you through the basic errors in JavaScript and explain the various errors you might encounter. You’ll then learn how to identify and fix these errors. There are also a couple of tips to handle errors effectively in production environments.

Without further ado, let’s begin!

Check Out Our Video Guide to Handling JavaScript Errors

What Are JavaScript Errors?

Errors in programming refer to situations that don’t let a program function normally. It can happen when a program doesn’t know how to handle the job at hand, such as when trying to open a non-existent file or reaching out to a web-based API endpoint while there’s no network connectivity.

These situations push the program to throw errors to the user, stating that it doesn’t know how to proceed. The program collects as much information as possible about the error and then reports that it can not move ahead.

Murphy’s law states that whatever can go wrong will eventually go wrong 😬 This applies a bit too well in the world of JavaScript 😅 Get prepped with this guide 👇Click to Tweet

Intelligent programmers try to predict and cover these scenarios so that the user doesn’t have to figure out a technical error message like “404” independently. Instead, they show a much more understandable message: “The page could not be found.”

Errors in JavaScript are objects shown whenever a programming error occurs. These objects contain ample information about the type of the error, the statement that caused the error, and the stack trace when the error occurred. JavaScript also allows programmers to create custom errors to provide extra information when debugging issues.

Properties of an Error

Now that the definition of a JavaScript error is clear, it’s time to dive into the details.

Errors in JavaScript carry certain standard and custom properties that help understand the cause and effects of the error. By default, errors in JavaScript contain three properties:

  1. message: A string value that carries the error message
  2. name: The type of error that occurred (We’ll dive deep into this in the next section)
  3. stack: The stack trace of the code executed when the error occurred.

Additionally, errors can also carry properties like columnNumber, lineNumber, fileName, etc., to describe the error better. However, these properties are not standard and may or may not be present in every error object generated from your JavaScript application.

Understanding Stack Trace

A stack trace is the list of method calls a program was in when an event such as an exception or a warning occurs. This is what a sample stack trace accompanied by an exception looks like:

The error “TypeError: Numeric argument is expected” is shown on a gray background with additional stack details.

Example of a Stack Trace.

As you can see, it starts by printing the error name and message, followed by a list of methods that were being called. Each method call states the location of its source code and the line at which it was invoked. You can use this data to navigate through your codebase and identify which piece of code is causing the error.

This list of methods is arranged in a stacked fashion. It shows where your exception was first thrown and how it propagated through the stacked method calls. Implementing a catch for the exception will not let it propagate up through the stack and crash your program. However, you might want to leave fatal errors uncaught to crash the program in some scenarios intentionally.

Errors vs Exceptions

Most people usually consider errors and exceptions as the same thing. However, it’s essential to note a slight yet fundamental difference between them.

To understand this better, let’s take a quick example. Here is how you can define an error in JavaScript:

const wrongTypeError = TypeError("Wrong type found, expected character")

And this is how the wrongTypeError object becomes an exception:

throw wrongTypeError

However, most people tend to use the shorthand form which defines error objects while throwing them:

throw TypeError("Wrong type found, expected character")

This is standard practice. However, it’s one of the reasons why developers tend to mix up exceptions and errors. Therefore, knowing the fundamentals is vital even though you use shorthands to get your work done quickly.

Types of Errors in JavaScript

There’s a range of predefined error types in JavaScript. They are automatically chosen and defined by the JavaScript runtime whenever the programmer doesn’t explicitly handle errors in the application.

This section will walk you through some of the most common types of errors in JavaScript and understand when and why they occur.

RangeError

A RangeError is thrown when a variable is set with a value outside its legal values range. It usually occurs when passing a value as an argument to a function, and the given value doesn’t lie in the range of the function’s parameters. It can sometimes get tricky to fix when using poorly documented third-party libraries since you need to know the range of possible values for the arguments to pass in the correct value.

Some of the common scenarios in which RangeError occurs are:

  • Trying to create an array of illegal lengths via the Array constructor.
  • Passing bad values to numeric methods like toExponential(), toPrecision(), toFixed(), etc.
  • Passing illegal values to string functions like normalize().

ReferenceError

A ReferenceError occurs when something is wrong with a variable’s reference in your code. You might have forgotten to define a value for the variable before using it, or you might be trying to use an inaccessible variable in your code. In any case, going through the stack trace provides ample information to find and fix the variable reference that is at fault.

Some of the common reasons why ReferenceErrors occur are:

  • Making a typo in a variable name.
  • Trying to access block-scoped variables outside of their scopes.
  • Referencing a global variable from an external library (like $ from jQuery) before it’s loaded.

SyntaxError

These errors are one of the simplest to fix since they indicate an error in the syntax of the code. Since JavaScript is a scripting language that is interpreted rather than compiled, these are thrown when the app executes the script that contains the error. In the case of compiled languages, such errors are identified during compilation. Thus, the app binaries are not created until these are fixed.

Some of the common reasons why SyntaxErrors might occur are:

  • Missing inverted commas
  • Missing closing parentheses
  • Improper alignment of curly braces or other characters

It’s a good practice to use a linting tool in your IDE to identify such errors for you before they hit the browser.

TypeError

TypeError is one of the most common errors in JavaScript apps. This error is created when some value doesn’t turn out to be of a particular expected type. Some of the common cases when it occurs are:

  • Invoking objects that are not methods.
  • Attempting to access properties of null or undefined objects
  • Treating a string as a number or vice versa

There are a lot more possibilities where a TypeError can occur. We’ll look at some famous instances later and learn how to fix them.

InternalError

The InternalError type is used when an exception occurs in the JavaScript runtime engine. It may or may not indicate an issue with your code.

More often than not, InternalError occurs in two scenarios only:

  • When a patch or an update to the JavaScript runtime carries a bug that throws exceptions (this happens very rarely)
  • When your code contains entities that are too large for the JavaScript engine (e.g. too many switch cases, too large array initializers, too much recursion)

The most appropriate approach to solve this error is to identify the cause via the error message and restructure your app logic, if possible, to eliminate the sudden spike of workload on the JavaScript engine.

URIError

URIError occurs when a global URI handling function such as decodeURIComponent is used illegally. It usually indicates that the parameter passed to the method call did not conform to URI standards and thus was not parsed by the method properly.

Diagnosing these errors is usually easy since you only need to examine the arguments for malformation.

EvalError

An EvalError occurs when an error occurs with an eval() function call. The eval() function is used to execute JavaScript code stored in strings. However, since using the eval() function is highly discouraged due to security issues and the current ECMAScript specifications don’t throw the EvalError class anymore, this error type exists simply to maintain backward compatibility with legacy JavaScript code.

If you’re working on an older version of JavaScript, you might encounter this error. In any case, it’s best to investigate the code executed in the eval() function call for any exceptions.

Creating Custom Error Types

While JavaScript offers an adequate list of error type classes to cover for most scenarios, you can always create a new error type if the list doesn’t satisfy your requirements. The foundation of this flexibility lies in the fact that JavaScript allows you to throw anything literally with the throw command.

So, technically, these statements are entirely legal:

throw 8
throw "An error occurred"

However, throwing a primitive data type doesn’t provide details about the error, such as its type, name, or the accompanying stack trace. To fix this and standardize the error handling process, the Error class has been provided. It’s also discouraged to use primitive data types while throwing exceptions.

You can extend the Error class to create your custom error class. Here is a basic example of how you can do this:

class ValidationError extends Error {
    constructor(message) {
        super(message);
        this.name = "ValidationError";
    }
}

And you can use it in the following way:

throw ValidationError("Property not found: name")

And you can then identify it using the instanceof keyword:

try {
    validateForm() // code that throws a ValidationError
} catch (e) {
    if (e instanceof ValidationError)
    // do something
    else
    // do something else
}

Top 10 Most Common Errors in JavaScript

Now that you understand the common error types and how to create your custom ones, it’s time to look at some of the most common errors you’ll face when writing JavaScript code.

Check Out Our Video Guide to The Most Common JavaScript Errors

1. Uncaught RangeError

This error occurs in Google Chrome under a few various scenarios. First, it can happen if you call a recursive function and it doesn’t terminate. You can check this out yourself in the Chrome Developer Console:

The error “Uncaught RangeError: Maximum call stack size exceeded” is shown on a red background beside a red cross icon with a recursive function’s code above it.

RangeError example with a recursive function call.

So to solve such an error, make sure to define the border cases of your recursive function correctly. Another reason why this error happens is if you have passed a value that is out of a function’s parameter’s range. Here’s an example:

The error “Uncaught RangeError: toExponential() argument must be between 0 and 100” is shown on a red background beside a red cross icon with a toExponential() function call above it.

RangeError example with toExponential() call.

The error message will usually indicate what is wrong with your code. Once you make the changes, it will be resolved.

num = 4. num.toExponential(2). Output: 4.00e+0.

Output for the toExponential() function call.

2. Uncaught TypeError: Cannot set property

This error occurs when you set a property on an undefined reference. You can reproduce the issue with this code:

var list
list.count = 0

Here’s the output that you’ll receive:

The error “Uncaught TypeError: Cannot set properties of undefined” is shown on a red background beside a red cross icon with a list.count = 0 assignment above it.

TypeError example.

To fix this error, initialize the reference with a value before accessing its properties. Here’s how it looks when fixed:

Setting list.count = 10 after initializing list with {} due to which the output is 10.

How to fix TypeError.

3. Uncaught TypeError: Cannot read property

This is one of the most frequently occurring errors in JavaScript. This error occurs when you attempt to read a property or call a function on an undefined object. You can reproduce it very easily by running the following code in a Chrome Developer console:

var func
func.call()

Here’s the output:

The error “Uncaught TypeError: Cannot read properties of undefined” is shown on a red background beside a red cross icon with func.call() above it.

TypeError example with undefined function.

An undefined object is one of the many possible causes of this error. Another prominent cause of this issue can be an improper initialization of the state while rendering the UI. Here’s a real-world example from a React application:

import React, { useState, useEffect } from "react";

const CardsList = () => {

    const [state, setState] = useState();

    useEffect(() => {
        setTimeout(() => setState({ items: ["Card 1", "Card 2"] }), 2000);
    }, []);

    return (
        <>
            {state.items.map((item) => (
                <li key={item}>{item}</li>
            ))}
        </>
    );
};

export default CardsList;

The app starts with an empty state container and is provided with some items after a delay of 2 seconds. The delay is put in place to imitate a network call. Even if your network is super fast, you’ll still face a minor delay due to which the component will render at least once. If you try to run this app, you’ll receive the following error:

The error “undefined is not an object” is shown on a grey background.

TypeError stack trace in a browser.

This is because, at the time of rendering, the state container is undefined; thus, there exists no property items on it. Fixing this error is easy. You just need to provide an initial default value to the state container.

// ...
const [state, setState] = useState({items: []});
// ...

Now, after the set delay, your app will show a similar output:

A bulleted list with two items reading "Card 1" and "Card 2".

Code output.

The exact fix in your code might be different, but the essence here is to always initialize your variables properly before using them.

4. TypeError: ‘undefined’ is not an object

This error occurs in Safari when you try to access the properties of or call a method on an undefined object. You can run the same code from above to reproduce the error yourself.

The error “TypeError: undefined is not an object” shown on a red background beside a red exclamation point icon with func.call() method call above it.

TypeError example with undefined function.

The solution to this error is also the same — make sure that you have initialized your variables correctly and they are not undefined when a property or method is accessed.

5. TypeError: null is not an object

This is, again, similar to the previous error. It occurs on Safari, and the only difference between the two errors is that this one is thrown when the object whose property or method is being accessed is null instead of undefined. You can reproduce this by running the following piece of code:

var func = null

func.call()

Here’s the output that you’ll receive:

The "TypeError: null is not an object" error message, shown on a red background beside a red exclamation point icon.

TypeError example with null function.

Since null is a value explicitly set to a variable and not assigned automatically by JavaScript. This error can occur only if you’re trying to access a variable you set null by yourself. So, you need to revisit your code and check if the logic that you wrote is correct or not.

6. TypeError: Cannot read property ‘length’

This error occurs in Chrome when you try to read the length of a null or undefined object. The cause of this issue is similar to the previous issues, but it occurs quite frequently while handling lists; hence it deserves a special mention. Here’s how you can reproduce the problem:

The error “Uncaught TypeError: Cannot read property 'length' of undefined” shown on a red background beside a red cross icon with myButton.length call above it.

TypeError example with an undefined object.

However, in the newer versions of Chrome, this error is reported as Uncaught TypeError: Cannot read properties of undefined. This is how it looks now:

The error “Uncaught TypeError: Cannot read properties of undefined” shown on a red background beside a red cross icon with myButton.length call above it.

TypeError example with an undefined object on newer Chrome versions.

The fix, again, is to ensure that the object whose length you’re trying to access exists and is not set to null.

7. TypeError: ‘undefined’ is not a function

This error occurs when you try to invoke a method that doesn’t exist in your script, or it does but can not be referenced in the calling context. This error usually occurs in Google Chrome, and you can solve it by checking the line of code throwing the error. If you find a typo, fix it and check if it solves your issue.

If you have used the self-referencing keyword this in your code, this error might arise if this is not appropriately bound to your context. Consider the following code:

function showAlert() {
    alert("message here")
}

document.addEventListener("click", () => {
    this.showAlert();
})

If you execute the above code, it will throw the error we discussed. It happens because the anonymous function passed as the event listener is being executed in the context of the document.

In contrast, the function showAlert is defined in the context of the window.

To solve this, you must pass the proper reference to the function by binding it with the bind() method:

document.addEventListener("click", this.showAlert.bind(this))

8. ReferenceError: event is not defined

This error occurs when you try to access a reference not defined in the calling scope. This usually happens when handling events since they often provide you with a reference called event in the callback function. This error can occur if you forget to define the event argument in your function’s parameters or misspell it.

This error might not occur in Internet Explorer or Google Chrome (as IE offers a global event variable and Chrome attaches the event variable automatically to the handler), but it can occur in Firefox. So it’s advisable to keep an eye out for such small mistakes.

9. TypeError: Assignment to constant variable

This is an error that arises out of carelessness. If you try to assign a new value to a constant variable, you’ll be met with such a result:

The error “Uncaught TypeError: Assignment to constant variable” shown on a red background beside a red cross icon with func = 6 assignment above it.

TypeError example with constant object assignment.

While it seems easy to fix right now, imagine hundreds of such variable declarations and one of them mistakenly defined as const instead of let! Unlike other scripting languages like PHP, there’s minimal difference between the style of declaring constants and variables in JavaScript. Therefore it’s advisable to check your declarations first of all when you face this error. You could also run into this error if you forget that the said reference is a constant and use it as a variable. This indicates either carelessness or a flaw in your app’s logic. Make sure to check this when trying to fix this issue.

10. (unknown): Script error

A script error occurs when a third-party script sends an error to your browser. This error is followed by (unknown) because the third-party script belongs to a different domain than your app. The browser hides other details to prevent leaking sensitive information from the third-party script.

You can not resolve this error without knowing the complete details. Here’s what you can do to get more information about the error:

  1. Add the crossorigin attribute in the script tag.
  2. Set the correct Access-Control-Allow-Origin header on the server hosting the script.
  3. [Optional] If you don’t have access to the server hosting the script, you can consider using a proxy to relay your request to the server and back to the client with the correct headers.

Once you can access the details of the error, you can then set down to fix the issue, which will probably be with either the third-party library or the network.

How to Identify and Prevent Errors in JavaScript

While the errors discussed above are the most common and frequent in JavaScript, you’ll come across, relying on a few examples can never be enough. It’s vital to understand how to detect and prevent any type of error in a JavaScript application while developing it. Here is how you can handle errors in JavaScript.

Manually Throw and Catch Errors

The most fundamental way of handling errors that have been thrown either manually or by the runtime is to catch them. Like most other languages, JavaScript offers a set of keywords to handle errors. It’s essential to know each of them in-depth before you set down to handle errors in your JavaScript app.

throw

The first and most basic keyword of the set is throw. As evident, the throw keyword is used to throw errors to create exceptions in the JavaScript runtime manually. We have already discussed this earlier in the piece, and here’s the gist of this keyword’s significance:

  • You can throw anything, including numbers, strings, and Error objects.
  • However, it’s not advisable to throw primitive data types such as strings and numbers since they don’t carry debug information about the errors.
  • Example: throw TypeError("Please provide a string")

try

The try keyword is used to indicate that a block of code might throw an exception. Its syntax is:

try {
    // error-prone code here
}

It’s important to note that a catch block must always follow the try block to handle errors effectively.

catch

The catch keyword is used to create a catch block. This block of code is responsible for handling the errors that the trailing try block catches. Here is its syntax:

catch (exception) {
    // code to handle the exception here
}

And this is how you implement the try and the catch blocks together:

try {
    // business logic code
} catch (exception) {
    // error handling code
}

Unlike C++ or Java, you can not append multiple catch blocks to a try block in JavaScript. This means that you can not do this:

try {
    // business logic code
} catch (exception) {
    if (exception instanceof TypeError) {
        // do something
    }
} catch (exception) {
    if (exception instanceof RangeError) {
    // do something
    }
}

Instead, you can use an if...else statement or a switch case statement inside the single catch block to handle all possible error cases. It would look like this:

try {
    // business logic code
} catch (exception) {
    if (exception instanceof TypeError) {
        // do something
    } else if (exception instanceof RangeError) {
        // do something else
    }
}

finally

The finally keyword is used to define a code block that is run after an error has been handled. This block is executed after the try and the catch blocks.

Also, the finally block will be executed regardless of the result of the other two blocks. This means that even if the catch block cannot handle the error entirely or an error is thrown in the catch block, the interpreter will execute the code in the finally block before the program crashes.

To be considered valid, the try block in JavaScript needs to be followed by either a catch or a finally block. Without any of those, the interpreter will raise a SyntaxError. Therefore, make sure to follow your try blocks with at least either of them when handling errors.

Handle Errors Globally With the onerror() Method

The onerror() method is available to all HTML elements for handling any errors that may occur with them. For instance, if an img tag cannot find the image whose URL is specified, it fires its onerror method to allow the user to handle the error.

Typically, you would provide another image URL in the onerror call for the img tag to fall back to. This is how you can do that via JavaScript:

const image = document.querySelector("img")

image.onerror = (event) => {
    console.log("Error occurred: " + event)
}

However, you can use this feature to create a global error handling mechanism for your app. Here’s how you can do it:

window.onerror = (event) => {
    console.log("Error occurred: " + event)
}

With this event handler, you can get rid of the multiple try...catch blocks lying around in your code and centralize your app’s error handling similar to event handling. You can attach multiple error handlers to the window to maintain the Single Responsibility Principle from the SOLID design principles. The interpreter will cycle through all handlers until it reaches the appropriate one.

Pass Errors via Callbacks

While simple and linear functions allow error handling to remain simple, callbacks can complicate the affair.

Consider the following piece of code:

const calculateCube = (number, callback) => {
    setTimeout(() => {
        const cube = number * number * number
        callback(cube)
    }, 1000)
}

const callback = result => console.log(result)

calculateCube(4, callback)

The above function demonstrates an asynchronous condition in which a function takes some time to process operations and returns the result later with the help of a callback.

If you try to enter a string instead of 4 in the function call, you’ll get NaN as a result.

This needs to be handled properly. Here’s how:

const calculateCube = (number, callback) => {

    setTimeout(() => {
        if (typeof number !== "number")
            throw new Error("Numeric argument is expected")

        const cube = number * number * number
        callback(cube)
    }, 1000)
}

const callback = result => console.log(result)

try {
    calculateCube(4, callback)
} catch (e) { console.log(e) }

This should solve the problem ideally. However, if you try passing a string to the function call, you’ll receive this:

The error “Uncaught Error: Numeric argument is expected” shown on a dark red background beside a red cross icon.

Error example with the wrong argument.

Even though you have implemented a try-catch block while calling the function, it still says the error is uncaught. The error is thrown after the catch block has been executed due to the timeout delay.

This can occur quickly in network calls, where unexpected delays creep in. You need to cover such cases while developing your app.

Here’s how you can handle errors properly in callbacks:

const calculateCube = (number, callback) => {

    setTimeout(() => {
        if (typeof number !== "number") {
            callback(new TypeError("Numeric argument is expected"))
            return
        }
        const cube = number * number * number
        callback(null, cube)
    }, 2000)
}

const callback = (error, result) => {
    if (error !== null) {
        console.log(error)
        return
    }
    console.log(result)
}

try {
    calculateCube('hey', callback)
} catch (e) {
    console.log(e)
}

Now, the output at the console will be:

The message “TypeError: Numeric argument is expected” shown on a dark grey background.

TypeError example with illegal argument.

This indicates that the error has been appropriately handled.

Handle Errors in Promises

Most people tend to prefer promises for handling asynchronous activities. Promises have another advantage — a rejected promise doesn’t terminate your script. However, you still need to implement a catch block to handle errors in promises. To understand this better, let’s rewrite the calculateCube() function using Promises:

const delay = ms => new Promise(res => setTimeout(res, ms));

const calculateCube = async (number) => {
    if (typeof number !== "number")
        throw Error("Numeric argument is expected")
    await delay(5000)
    const cube = number * number * number
    return cube
}

try {
    calculateCube(4).then(r => console.log(r))
} catch (e) { console.log(e) }

The timeout from the previous code has been isolated into the delay function for understanding. If you try to enter a string instead of 4, the output that you get will be similar to this:

The error “Uncaught (in promise) Error: Numeric argument is expected” shown on a dark grey background beside a red cross icon.

TypeError example with an illegal argument in Promise.

Again, this is due to the Promise throwing the error after everything else has completed execution. The solution to this issue is simple. Simply add a catch() call to the promise chain like this:

calculateCube("hey")
.then(r => console.log(r))
.catch(e => console.log(e))

Now the output will be:

The message “Error: Numeric argument is expected” shown on a dark grey background.

Handled TypeError example with illegal argument.

You can observe how easy it is to handle errors with promises. Additionally, you can chain a finally() block and the promise call to add code that will run after error handling has been completed.

Alternatively, you can also handle errors in promises using the traditional try-catch-finally technique. Here’s how your promise call would look like in that case:

try {
    let result = await calculateCube("hey")
    console.log(result)
} catch (e) {
    console.log(e)
} finally {
    console.log('Finally executed")
}

However, this works inside an asynchronous function only. Therefore the most preferred way to handle errors in promises is to chain catch and finally to the promise call.

throw/catch vs onerror() vs Callbacks vs Promises: Which is the Best?

With four methods at your disposal, you must know how to choose the most appropriate in any given use case. Here’s how you can decide for yourselves:

throw/catch

You will be using this method most of the time. Make sure to implement conditions for all possible errors inside your catch block, and remember to include a finally block if you need to run some memory clean-up routines after the try block.

However, too many try/catch blocks can make your code difficult to maintain. If you find yourself in such a situation, you might want to handle errors via the global handler or the promise method.

When deciding between asynchronous try/catch blocks and promise’s catch(), it’s advisable to go with the async try/catch blocks since they will make your code linear and easy to debug.

onerror()

It’s best to use the onerror() method when you know that your app has to handle many errors, and they can be well-scattered throughout the codebase. The onerror method enables you to handle errors as if they were just another event handled by your application. You can define multiple error handlers and attach them to your app’s window on the initial rendering.

However, you must also remember that the onerror() method can be unnecessarily challenging to set up in smaller projects with a lesser scope of error. If you’re sure that your app will not throw too many errors, the traditional throw/catch method will work best for you.

Callbacks and Promises

Error handling in callbacks and promises differs due to their code design and structure. However, if you choose between these two before you have written your code, it would be best to go with promises.

This is because promises have an inbuilt construct for chaining a catch() and a finally() block to handle errors easily. This method is easier and cleaner than defining additional arguments/reusing existing arguments to handle errors.

Keep Track of Changes With Git Repositories

Many errors often arise due to manual mistakes in the codebase. While developing or debugging your code, you might end up making unnecessary changes that may cause new errors to appear in your codebase. Automated testing is a great way to keep your code in check after every change. However, it can only tell you if something’s wrong. If you don’t take frequent backups of your code, you’ll end up wasting time trying to fix a function or a script that was working just fine before.

This is where git plays its role. With a proper commit strategy, you can use your git history as a backup system to view your code as it evolved through the development. You can easily browse through your older commits and find out the version of the function working fine before but throwing errors after an unrelated change.

You can then restore the old code or compare the two versions to determine what went wrong. Modern web development tools like GitHub Desktop or GitKraken help you to visualize these changes side by side and figure out the mistakes quickly.

A habit that can help you make fewer errors is running code reviews whenever you make a significant change to your code. If you’re working in a team, you can create a pull request and have a team member review it thoroughly. This will help you use a second pair of eyes to spot out any errors that might have slipped by you.

Best Practices for Handling Errors in JavaScript

The above-mentioned methods are adequate to help you design a robust error handling approach for your next JavaScript application. However, it would be best to keep a few things in mind while implementing them to get the best out of your error-proofing. Here are some tips to help you.

1. Use Custom Errors When Handling Operational Exceptions

We introduced custom errors early in this guide to give you an idea of how to customize the error handling to your application’s unique case. It’s advisable to use custom errors wherever possible instead of the generic Error class as it provides more contextual information to the calling environment about the error.

On top of that, custom errors allow you to moderate how an error is displayed to the calling environment. This means that you can choose to hide specific details or display additional information about the error as and when you wish.

You can go so far as to format the error contents according to your needs. This gives you better control over how the error is interpreted and handled.

2. Do Not Swallow Any Exceptions

Even the most senior developers often make a rookie mistake — consuming exceptions levels deep down in their code.

You might come across situations where you have a piece of code that is optional to run. If it works, great; if it doesn’t, you don’t need to do anything about it.

In these cases, it’s often tempting to put this code in a try block and attach an empty catch block to it. However, by doing this, you’ll leave that piece of code open to causing any kind of error and getting away with it. This can become dangerous if you have a large codebase and many instances of such poor error management constructs.

The best way to handle exceptions is to determine a level on which all of them will be dealt and raise them until there. This level can be a controller (in an MVC architecture app) or a middleware (in a traditional server-oriented app).

This way, you’ll get to know where you can find all the errors occurring in your app and choose how to resolve them, even if it means not doing anything about them.

3. Use a Centralized Strategy for Logs and Error Alerts

Logging an error is often an integral part of handling it. Those who fail to develop a centralized strategy for logging errors may miss out on valuable information about their app’s usage.

An app’s event logs can help you figure out crucial data about errors and help to debug them quickly. If you have proper alerting mechanisms set up in your app, you can know when an error occurs in your app before it reaches a large section of your user base.

It’s advisable to use a pre-built logger or create one to suit your needs. You can configure this logger to handle errors based on their levels (warning, debug, info, etc.), and some loggers even go so far as to send logs to remote logging servers immediately. This way, you can watch how your application’s logic performs with active users.

4. Notify Users About Errors Appropriately

Another good point to keep in mind while defining your error handling strategy is to keep the user in mind.

All errors that interfere with the normal functioning of your app must present a visible alert to the user to notify them that something went wrong so the user can try to work out a solution. If you know a quick fix for the error, such as retrying an operation or logging out and logging back in, make sure to mention it in the alert to help fix the user experience in real-time.

In the case of errors that don’t cause any interference with the everyday user experience, you can consider suppressing the alert and logging the error to a remote server for resolving later.

5. Implement a Middleware (Node.js)

The Node.js environment supports middlewares to add functionalities to server applications. You can use this feature to create an error-handling middleware for your server.

The most significant benefit of using middleware is that all of your errors are handled centrally in one place. You can choose to enable/disable this setup for testing purposes easily.

Here’s how you can create a basic middleware:

const logError = err => {
    console.log("ERROR: " + String(err))
}

const errorLoggerMiddleware = (err, req, res, next) => {
    logError(err)
    next(err)
}

const returnErrorMiddleware = (err, req, res, next) => {
    res.status(err.statusCode || 500)
       .send(err.message)
}

module.exports = {
    logError,
    errorLoggerMiddleware,
    returnErrorMiddleware
}

You can then use this middleware in your app like this:

const { errorLoggerMiddleware, returnErrorMiddleware } = require('./errorMiddleware')

app.use(errorLoggerMiddleware)

app.use(returnErrorMiddleware)

You can now define custom logic inside the middleware to handle errors appropriately. You don’t need to worry about implementing individual error handling constructs throughout your codebase anymore.

6. Restart Your App To Handle Programmer Errors (Node.js)

When Node.js apps encounter programmer errors, they might not necessarily throw an exception and try to close the app. Such errors can include issues arising from programmer mistakes, like high CPU consumption, memory bloating, or memory leaks. The best way to handle these is to gracefully restart the app by crashing it via the Node.js cluster mode or a unique tool like PM2. This can ensure that the app doesn’t crash upon user action, presenting a terrible user experience.

7. Catch All Uncaught Exceptions (Node.js)

You can never be sure that you have covered every possible error that can occur in your app. Therefore, it’s essential to implement a fallback strategy to catch all uncaught exceptions from your app.

Here’s how you can do that:

process.on('uncaughtException', error => {
    console.log("ERROR: " + String(error))
    // other handling mechanisms
})

You can also identify if the error that occurred is a standard exception or a custom operational error. Based on the result, you can exit the process and restart it to avoid unexpected behavior.

8. Catch All Unhandled Promise Rejections (Node.js)

Similar to how you can never cover for all possible exceptions, there’s a high chance that you might miss out on handling all possible promise rejections. However, unlike exceptions, promise rejections don’t throw errors.

So, an important promise that was rejected might slip by as a warning and leave your app open to the possibility of running into unexpected behavior. Therefore, it’s crucial to implement a fallback mechanism for handling promise rejection.

Here’s how you can do that:

const promiseRejectionCallback = error => {
    console.log("PROMISE REJECTED: " + String(error))
}

process.on('unhandledRejection', callback)

If you create an application, there are chances that you’ll create bugs and other issues in it as well. 😅 Learn how to handle them with help from this guide ⬇️Click to Tweet

Summary

Like any other programming language, errors are quite frequent and natural in JavaScript. In some cases, you might even need to throw errors intentionally to indicate the correct response to your users. Hence, understanding their anatomy and types is very crucial.

Moreover, you need to be equipped with the right tools and techniques to identify and prevent errors from taking down your application.

In most cases, a solid strategy to handle errors with careful execution is enough for all types of JavaScript applications.

Are there any other JavaScript errors that you still haven’t been able to resolve? Any techniques for handling JS errors constructively? Let us know in the comments below!


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Временами работа над кодом JavaScript заставляет чувствовать себя выдохшимся и измождённым, поэтому некоторые подсказки по отладке никогда не будут лишними. На примерах из песен мы постараемся разобрать типичные ошибки в коде на JS и способы, которыми их можно найти и устранить.

Свойство не определено

let girl = {
    name: "Lucky",
    location: "Hollywood",
    profession: "star",
    thingsMissingInHerLife: true,
    lovely: true,
    cry: function() {
        return "cry, cry, cries in her lonely heart"
    }
}

console.log(girl.named.lucky)

Этот код выдаёт ошибку «Uncaught TypeError: Cannot read property ‘lucky’ of undefined». Дело в том, что объект girl не имеет свойства named, хотя у него есть свойство name. Поскольку свойство girl.named не определено, мы не можем получить к нему доступ, то есть оно просто не существует. Если мы заменим girl.named.lucky на girl.name, то код вернёт нам «Lucky».

Свойство — некоторое значение, привязанное к объекту JavaScript. Почитать больше об объектах можно здесь (статья на английском языке).

Отладка ошибок TypeError

Ошибки типа TypeError появляются, когда вы пытаетесь выполнить действия с данными, которые не соответствуют нужному типу, например применяете .bold() к числу, запрашиваете свойство undefined или пытаетесь вызвать как функцию что-то, не являющееся функцией. Например, вы увидите такую ошибку, если вызовете girl(), поскольку это объект, а не функция. В последнем случае вы получите «Uncaught TypeError: yourVariable.bold is not a function» и «girl is not a function».

Для отладки этих ошибок надо разобраться с переменными. Что такое girl? И что такое girl.named? Вы можете понять это изучая код, выводя переменные с помощью console.log, используя команду debugger или просто напечатав имя переменной в консоли. Удостоверьтесь, что вы можете манипулировать содержащимся в переменной типом данных. Если тип данных не подходит, модифицируйте его нужным образом, добавьте условие или блок try..catch, чтобы контролировать выполнение операции, или используйте эту операцию на другом объекте.

Переполнение стека

Если верить авторам песни «Baby One More Time», слово «hit» в строчке «Hit me baby, one more time» означает «позвони», то есть Бритни хочет, чтобы её бывший позвонил ей ещё раз. Это, возможно, приведёт к ещё большему количеству звонков в будущем. По сути это рекурсия, которая может вызвать ошибку в случае переполнения стека вызовов.

Конкретные сообщения об ошибке зависят от браузера, но выглядят они примерно так:

Error: Out of stack space (Edge)
InternalError: too much recursion (Firefox)
RangeError: Maximum call stack size exceeded (Chrome)

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

function oneMoreTime(stillBelieve=true, loneliness=0) {
    if (!stillBelieve && loneliness < 0) return
    loneliness++
    return oneMoreTime(stillBelieve, loneliness)
}

В показанной выше функции stillBelieve никогда не примет значение false, и поэтому мы раз за разом будем вызывать oneMoreTime, увеличивая одиночество, и никогда не завершим выполнение функции.

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

function oneMoreTime(stillBelieve=true, loneliness=0) {
    if (!stillBelieve && loneliness < 0) return
    loneliness--
    stillBelieve = false
    return oneMoreTime(stillBelieve, loneliness)
}

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

let worldEnded = false

while (worldEnded !== true) {
  console.log("Keep on dancin' till the world ends")
}

Исправить это можно примерно так же, как и предыдущий пример.

let worldEnded = false

while (worldEnded !== true) {
  console.log("Keep on dancin' till the world ends")
  worldEnded = true
}

Отладка бесконечных циклов и рекурсий

Для начала, если возникла проблема с бесконечным циклом, закройте вкладку, если вы пользуетесь Chrome или Edge, или окно браузера, если у вас Firefox. Затем просмотрите код: есть ли там что-то, что создаёт бесконечный цикл или рекурсию. Если ничего не обнаружили — добавьте в цикл или функцию команду debugger и проверьте значение переменных на нескольких начальных итерациях. Если они не соответствуют ожидаемым, вы это обнаружите.

В приведённом выше примере стоило бы добавить debugger самой первой строкой функции или цикла. Затем нужно открыть отладочную вкладку в Chrome и изучить переменные в Scope. С помощью кнопки «next» можно проследить, как они меняются с каждой итерацией. Обычно это помогает найти решение проблемы.

Здесь можно найти руководство на английском языке по отладке с помощью Chrome’s DevTools, а здесь — для Firefox.

Ошибка синтаксиса

SyntaxError — вероятно самая распространённая разновидность ошибок в JavaScript. Эти ошибки возникают, если вы не соблюдаете правила синтаксиса языка. Копируя посыл песни Бритни «Everytime», JavaScript говорит отсутствующим скобкам и кавычкам: «Вы нужны мне, крошки».

Соответствующие расширения текстового редактора помогут избежать ошибок. Bracket Pair Colorizer размечает скобки в коде разными цветами, а Prettier или другой инструмент статического анализа кода поможет быстро найти ошибки. Постарайтесь придерживаться правильной разметки и делайте блоки кода как можно короче и с минимальной вложенностью. Такой подход сильно облегчает отладку.

Теперь, вооружившись новыми навыками отладки, вы станете немного сильнее в JavaScript, чем были вчера.

Перевод статьи Oops, I did it again: A guide to debugging common JavaScript errors

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

От автора: чтобы вернуть сообщество разработчиков, мы рассмотрели нашу базу данных по тысячам проектов и нашли 10 самых распространённых ошибок в JavaScript. Мы собираемся показать вам, что к ним приводит и как это предотвратить. Если ни одна ошибка JavaScript не встречается в вашем коде, это делает вас лучшим разработчиком.

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

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

Вот первые 10 ошибок JavaScript:

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

Узнать подробнее

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

1. Uncaught TypeError: Cannot read property

Если вы разработчик JavaScript, то, вероятно, видели эту ошибку очень много раз. Это происходит в Chrome, когда вы читаете свойство или вызываете метод на неопределенный объект. Это можно очень легко проверить в консоли разработчика Chrome.

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

Это может произойти по многим причинам, но чаще всего это неправильная инициализация состояния при рендеринге компонентов пользовательского интерфейса. Давайте рассмотрим пример того, как это может произойти в реальном приложении. Мы выберем React, но те же принципы неправильной инициализации применимы и к Angular, Vue или любой другой структуре.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

class Quiz extends Component {

  componentWillMount() {

    axios.get(‘/thedata’).then(res => {

      this.setState({items: res.data});

    });

  }

  render() {

    return (

      <ul>

        {this.state.items.map(item =>

          <li key={item.id}>{item.name}</li>

        )}

      </ul>

    );

  }

}

Здесь понимаются две важные вещи:

Состояние компонента (например, this.state ) начинает жизнь как undefined.

Когда вы извлекаете данные асинхронно, компонент будет отображаться как минимум один раз перед загрузкой данных — независимо от того, выбрана ли она в конструкторе componentWillMount или componentDidMount . Когда Quiz отображается впервые, this.state.items не определен. Это, в свою очередь, означает, что ItemList получает элементы как неопределенные, и вы получаете сообщение об ошибке «Uncaught TypeError: Невозможно прочитать карту свойств» в консоли.

Это легко исправить. Самый простой способ: инициализировать состояние с разумными значениями по умолчанию в конструкторе.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

class Quiz extends Component {

  // Added this:

  constructor(props) {

    super(props);

    // Assign state itself, and a default value for items

    this.state = {

      items: []

    };

  }

  componentWillMount() {

    axios.get(‘/thedata’).then(res => {

      this.setState({items: res.data});

    });

  }

  render() {

    return (

      <ul>

        {this.state.items.map(item =>

          <li key={item.id}>{item.name}</li>

        )}

      </ul>

    );

  }

}

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

2. TypeError: ‘undefined’ is not an object (evaluating

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

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

3. TypeError: null is not an object (evaluating

Это ошибка, которая возникает в Safari при чтении свойства или вызове метода для пустого объекта. Проверить это можно в консоли разработчика Safari.

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

Интересно, что в JavaScript значения null и undefined не совпадают, поэтому мы видим два разных сообщения об ошибках. Undefined обычно является переменной, которая не была назначена, а null означает, что значение пустое. Чтобы убедиться, что они не одно и то же, попробуйте использовать строгий оператор равенства:

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

Один из способов, которым эта ошибка может возникнуть в реальном мире — это попытка использовать элемент DOM в JavaScript перед загрузкой элемента. Это потому, что DOM API возвращает null для ссылок на пустые объекты.

Любой JS-код, который выполняет и обрабатывает элементы DOM, должен выполняться после создания элементов DOM. JS-код интерпретируется сверху вниз, как изложено в HTML. Итак, если перед элементами DOM есть тег, код JS в теге скрипта будет выполняться, когда браузер анализирует HTML-страницу. Вы получите эту ошибку, если элементы DOM не были созданы до загрузки сценария.

В этом примере мы можем решить проблему, добавив прослушиватель событий, который уведомит нас, когда страница будет готова. После addEventListener метод init() может использовать элементы DOM.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<script>

  function init() {

    var myButton = document.getElementById(«myButton»);

    var myTextfield = document.getElementById(«myTextfield»);

    myButton.onclick = function() {

      var userName = myTextfield.value;

    }

  }

  document.addEventListener(‘readystatechange’, function() {

    if (document.readyState === «complete») {

      init();

    }

  });

</script>

<form>

  <input type=«text» id=«myTextfield» placeholder=«Type your name» />

  <input type=«button» id=«myButton» value=«Go» />

</form>

4. (unknown): Script error

Ошибка скрипта возникает, когда ошибка неперехваченного JavaScript пересекает границы домена и нарушает политику перекрестного происхождения. Например, если вы размещаете свой код JavaScript на CDN, любые неперехваченные ошибки (ошибки, которые появляются в обработчике window.onerror, вместо того, чтобы быть пойманным в try-catch) будут переданы как просто «Script error» вместо того, чтобы содержать полезную информацию. Эта мера безопасности браузера предназначена для предотвращения передачи данных по доменам, которые в противном случае не были бы допущены к коммуникации.

Чтобы получить реальные сообщения об ошибках, выполните следующие действия:

1. Отправьте заголовок Access-Control-Allow-Origin

Установка заголовка Access-Control-Allow-Origin в * означает, что к ресурсу можно получить доступ из любого домена. Вы можете заменить * своим доменом, если необходимо: например, Access-Control-Allow-Origin: www.example.com . Если вы используете CDN из-за проблем с кэшированием, которые могут возникнуть, обработка нескольких доменов становится сложной и нельзя не приложить усилий. Подробнее см. здесь.

Вот несколько примеров того, как установить этот заголовок в различных средах:

Apache

В папках, где будут храниться ваши файлы JavaScript, создайте файл .htaccess со следующим содержимым:

Header add AccessControlAllowOrigin «*»

Nginx

Добавьте директиву add_header в блок местоположения, который служит файлам JavaScript:

location ~ ^/assets/ { add_header AccessControlAllowOrigin *; }

HAProxy

Добавьте в ресурс, где будут загружены файлы JavaScript:

rspadd AccessControlAllowOrigin: *

2. Установите crossorigin = «anonymous» в теге скрипта

В HTML-источнике для каждого из сценариев, где вы установите заголовок Access-Control-Allow-Origin, в теге SCRIPT установите crossorigin=»anonymous». Убедитесь, что заголовок отправляется для файла сценария, перед добавлением свойства crossorigin в тег скрипта. В Firefox, если атрибут crossorigin присутствует, но заголовок Access-Control-Allow-Origin отсутствует, сценарий не будет выполнен.

5. TypeError: Object doesn’t support property

Это ошибка, которая возникает в IE при вызове неопределенного метода. Вы можете проверить это в IE Developer Console.

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

Это эквивалентно ошибке «TypeError: ‘undefined’ is not a function» в Chrome. Да, разные браузеры могут иметь разные сообщения для одной и той же ошибки.

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

Узнать подробнее

Это обычная проблема для IE в веб-приложениях, использующих пространство имен JavaScript. Когда это так, проблема в 99,9% случаев— это неспособность IE связать методы в текущем пространстве имен с ключевым словом this. Например, если у вас есть пространство имен имен Rollbar с помощью метода isAwesome. Обычно, если вы находитесь в пространстве имен Rollbar вы можете вызвать метод isAwesome со следующим синтаксисом:

Chrome, Firefox и Opera с радостью согласятся с этим синтаксисом. С другой стороны, IE не станет. Таким образом, самая безопасная ставка при использовании JS namespacing — это префикс с фактическим пространством имен.

6. TypeError: ‘undefined’ is not a function

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

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

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

Рассмотрим фрагмент кода:

function clearBoard(){

  alert(«Cleared»);

}

document.addEventListener(«click», function(){

  this.clearBoard(); // what is “this” ?

});

Выполнение вышеуказанного кода приводит к следующей ошибке: «Uncaught TypeError: undefined is not function». Причина, по которой вы получаете эту ошибку, заключается в том, что при вызове setTimeout() вы вызываете window.setTimeout(). В результате анонимная функция, передаваемая setTimeout(), определяется в контексте объекта окна, у которого нет clearBoard().

Традиционное решение, совместимое со старым браузером — просто сохранить ссылку на this в переменной, которая затем может быть унаследована закрытием. Например:

var self=this;  // save reference to ‘this’, while it’s still this!

document.addEventListener(«click», function(){

  self.clearBoard();

});

Кроме того, в новых браузерах для передачи правильной ссылки вы можете использовать метод bind():

document.addEventListener(«click»,this.clearBoard.bind(this));

7. Uncaught RangeError: Maximum call stack

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

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

Это также может произойти, если вы передадите значение функции, находящейся за пределами допустимого диапазона. Многие функции принимают только определенный диапазон чисел для своих входных значений. Например, Number.toExponential(digits) и N umber.toFixed(digits) принимают цифры от 0 до 20, а Number.toPrecision(digits) принимают цифры от 1 до 21.

var a = new Array(4294967295);  //OK

var b = new Array(1); //range error

var num = 2.555555;

document.writeln(num.toExponential(4));  //OK

document.writeln(num.toExponential(2)); //range error!

num = 2.9999;

document.writeln(num.toFixed(2));   //OK

document.writeln(num.toFixed(25));  //range error!

num = 2.3456;

document.writeln(num.toPrecision(1));   //OK

document.writeln(num.toPrecision(22));  //range error!

8. TypeError: Cannot read property ‘length’

Это ошибка, которая возникает в Chrome из-за свойства длины чтения для неопределенной переменной. Вы можете протестировать это в консоли разработчика Chrome.

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

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

var testArray= [«Test»];

function testFunction(testArray) {

    for (var i = 0; i < testArray.length; i++) {

      console.log(testArray[i]);

    }

}

testFunction();

Когда вы объявляете функцию с параметрами, эти параметры становятся локальными. Это означает, что даже если у вас есть переменные с именами testArray , параметры с одинаковыми именами внутри функции будут по-прежнему рассматриваться как локальные.

У вас есть два способа решить эту проблему:

1. Удалите параметры в объявлении функции (оказывается, вы хотите получить доступ к тем переменным, которые объявлены вне функции, поэтому вам не нужны параметры для вашей функции):

var testArray = [«Test»];

/* Precondition: defined testArray outside of a function */

function testFunction(/* No params */) {

    for (var i = 0; i < testArray.length; i++) {

      console.log(testArray[i]);

    }

}

testFunction();

2. Вызовите функцию, передав ей массив, который мы объявили:

var testArray = [«Test»];

function testFunction(testArray) {

   for (var i = 0; i < testArray.length; i++) {

      console.log(testArray[i]);

    }

}

testFunction(testArray);

9. Uncaught TypeError: Cannot set property

Когда мы пытаемся получить доступ к неопределенной переменной, она всегда возвращает undefined, а мы не можем получить или установить любое свойство undefined. В этом случае приложение будет выбрасывать “Uncaught TypeError cannot set property of undefined.”

Например, в браузере Chrome:

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

Если объект test не существует, будет выдаваться ошибка: “Uncaught TypeError cannot set property of undefined.”

10. ReferenceError: event is not defined

Эта ошибка возникает при попытке получить доступ к переменной, которая не определена или находится за пределами текущей области. Вы можете легко протестировать её в браузере Chrome.

Топ-10 ошибок JavaScript из 1000+ проектов (и как их избежать)

Если вы получаете эту ошибку при использовании системы обработки событий, убедитесь, что вы используете объект события, переданный в качестве параметра. Старые браузеры, такие как IE, предлагают событие глобальной переменной, но не поддерживаются во всех браузерах. Библиотеки, подобные jQuery, пытаются нормализовать это поведение. Тем не менее, лучше использовать тот объект, который передается в функцию обработчика событий.

document.addEventListener(«mousemove», function (event) {

  console.log(event);

})

Вывод

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

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

Автор: Jason Skowronski

Источник: //rollbar.com/

Редакция: Команда webformyself.

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

Узнать подробнее

JavaScript. Быстрый старт

Изучите основы JavaScript на практическом примере по созданию веб-приложения

Смотреть

Существует ряд причин, по которым код JavaScript может вызывать ошибки, например:

  • Проблема с сетевым подключением;
  • Пользователь мог ввести неверное значение в поля формы;
  • Ссылка на объекты или функции, которые не существуют;
  • Неправильные данные отправляются или принимаются с веб-сервера;
  • Служба, к которой приложение должно получить доступ, может быть временно недоступна.

Эти типы ошибок известны как ошибки времени выполнения (runtime errors), поскольку они возникают во время выполнения скрипта. Профессиональное приложение должно иметь возможность корректно обрабатывать такие ошибки во время выполнения. Обычно это означает понятное информирование пользователя о возникшей проблеме.

Оператор try…catch

JavaScript предоставляет оператор try-catch, чтобы перехватывать ошибки времени выполнения и корректно их обработать.

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

try {
    // Код, который может вызвать ошибку
} catch(error) {
    // Действие, которое нужно выполнить при возникновении ошибки
}

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

Следующий пример демонстрирует, как работает оператор try-catch:

try {
    var greet = "Hi, there!";
    document.write(greet);
    
    // Попытка получить доступ к несуществующей переменной
    document.write(welcome);
    
    // Если произошла ошибка, следующая строка не будет выполнена
    alert("All statements are executed successfully.");
} catch(error) {
    // Обработка ошибки
  alert("Caught error: " + error.message);
}
 
// Продолжаем исполнение кода
document.write("<p>Hello World!</p>");

Приведенный выше скрипт генерирует ошибку, которая отображается в диалоговом окне с предупреждением, а не выводится в консоль браузера. Кроме того, программа не остановилась внезапно, даже если произошла ошибка.

Также обратите внимание, что за ключевым словом catch указывается идентификатор в скобках. Этот идентификатор действует как параметр функции. При возникновении ошибки интерпретатор JavaScript генерирует объект, содержащий сведения о нем. Этот объект ошибки затем передается в качестве аргумента для обработки.

Оператор try-catch является механизмом обработки исключений. Исключением является сигнал, который указывает, что во время выполнения программы возникли какие-то исключительные условия или ошибки. Термины «исключение» и «ошибка» часто используются взаимозаменяемо.

Оператор try…catch…finally

Оператор try-catch также может содержать предложение finally. Код внутри блока finally всегда будет выполняться независимо от того, произошла ошибка в блоке try или нет.

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

// Присвоение значения, возвращаемого диалоговым окном
var num = prompt("Enter a positive integer between 0 to 100");

// Запоминание времени начала исполнения
var start = Date.now();

try {
    if(num > 0 && num <= 100) {
        alert(Math.pow(num, num)); // the base to the exponent power
    } else {
        throw new Error("An invalid value is entered!");
    }
} catch(e) {
    alert(e.message);
} finally {
    // Отображение времени, необходимого для выполнения кода
    alert("Execution took: " + (Date.now() - start) + "ms");
}

Вызов ошибок с помощью оператора throw

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

Общий синтаксис оператора throw: throw expression;

Выражение expression может быть объектом или значением любого типа данных. Однако лучше использовать объекты, желательно со свойствами name и message. Встроенный в JavaScript конструктор Error() предоставляет удобный способ создания объекта ошибки. Давайте посмотрим на некоторые примеры:

throw 123;
throw "Missing values!";
throw true;
throw { name: "InvalidParameter", message: "Parameter is not a number!" };
throw new Error("Something went wrong!");

Если вы используете встроенные в JavaScript функции конструктора ошибок (например, Error(), TypeError() и т. д.) для создания объектов ошибок, тогда свойство name совпадает с именем конструктора, а message равно аргументу функции конструктора.

Теперь мы собираемся создать функцию squareRoot(), чтобы найти квадратный корень числа. Это можно сделать просто с помощью встроенной в JavaScript функции Math.sqrt(), но проблема здесь в том, что она возвращает NaN для отрицательных чисел, не давая никаких подсказок о том, что пошло не так.

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

function squareRoot(number) {
    // Выдает ошибку, если число отрицательное
    if(number < 0) {
        throw new Error("Sorry, can't calculate square root of a negative number.");
    } else {
        return Math.sqrt(number);
    }
}
    
try {
    squareRoot(16);
    squareRoot(625);
    squareRoot(-9);
    squareRoot(100);
    
    // Если выдается ошибка, следующая строка не будет выполнена
    alert("All calculations are performed successfully.");
} catch(e) {
    // Обработка ошибки
    alert(e.message);
}

Теоретически можно вычислить квадратный корень из отрицательного числа, используя мнимое число i, где i2 = -1. Следовательно, квадратный корень из -4 равен 2i, квадратный корень из -9 равен 3i и так далее. Но мнимые числа не поддерживаются в JavaScript.

Типы ошибок

Объект Error является базовым типом всех ошибок и имеет два основных свойства: name, указывающее тип ошибки и свойство message, которое содержит сообщение, описывающее ошибку более подробно. Любая выданная ошибка будет экземпляром объекта Error.

Существует несколько различных типов ошибок, которые могут возникнуть во время выполнения программы JavaScript, например RangeError, ReferenceError, SyntaxError, TypeError, и URIError.

В следующем разделе описывается каждый из этих типов ошибок более подробно:

RangeError

RangeError генерируется, когда вы используете число, выходящее за пределы допустимых значений. Например, создание массива с отрицательной длиной вызовет RangeError.

var num = 12.735;
num.toFixed(200); // выдает ошибку диапазона (допустимый диапазон от 0 до 100)

var array = new Array(-1); // выдает ошибку диапазона

ReferenceError

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

var firstName = "Harry";
console.log(firstname); // выдает ошибку ссылки (имена переменных чувствительны к регистру)

undefinedObj.getValues(); // выдает ошибку ссылки

nonexistentArray.length; // выдает ошибку ссылки

SyntaxError

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

var array = ["a", "b", "c"];
document.write(array.slice(2); // выдает синтаксическую ошибку (отсутствует скобка)

alert("Hello World!'); // выдает синтаксическую ошибку (несоответствие кавычек)

TypeError

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

var num = 123;
num.toLowerCase(); /* выдает ошибку (поскольку toLowerCase() является строковым методом, число не может быть преобразовано в нижний регистр) */

var greet = "Hello World!"
greet.join() // выдает ошибку (так как join() является методом массива)

URIError

URIError генерируется, когда вы указали недопустимый URI (расшифровывается как Uniform Resource Identifier) для функций, связанных с URI, таких как encodeURI() или decodeURI(), как показано здесь:

var a = "%E6%A2%B";
decodeURI(a);  // выдает ошибку URI

var b = "uD800";
encodeURI(b);   // выдает ошибку URI

Существует еще один тип ошибки EvalError, который генерируется при возникновении ошибки во время выполнения кода с помощью функции eval(). Хотя эта ошибка больше не генерируется JavaScript, этот объект все еще остается для обратной совместимости.

Конкретный тип ошибки также может быть выдан вручную с использованием соответствующего конструктора и оператора throw. Например, чтобы сгенерировать ошибку TypeError, вы можете использовать конструктор TypeError(), например:

var num = prompt("Please enter a number");

try {
    if(num != "" && num !== null && isFinite(+num)) {
        alert(Math.exp(num));
    } else {
        throw new TypeError("You have not entered a number.");
    }
} catch(e) {
    alert(e.name);
    alert(e.message);
    alert(e.stack); // нестандартное свойство
}

Объект Error также поддерживает некоторые нестандартные свойства. Одним из наиболее широко используемых таких свойств является: stack trace, который возвращает трассировку стека для этой ошибки. Вы можете использовать его в целях отладки, но не используйте его на рабочих сайтах.

Понравилась статья? Поделить с друзьями:
  • Ошибка при выполнении error clear
  • Ошибка при выполнении приложения сервера что это значит
  • Ошибка при выполнение метода подключить обработку код ошибки 10 000
  • Ошибка при выплате зарплаты как ее исправить
  • Ошибка при выключении компьютера windows 10 память не может быть read