Error uncaught error header is wrong

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

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

Просмотры 389K

JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!

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

Как читать ошибки?

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

Типичная ошибка из Chrome выглядит так:

Uncaught TypeError: undefined is not a function

Структура ошибки следующая:

  1. Uncaught TypeError: эта часть сообщения обычно не особо полезна. Uncaught значит, что ошибка не была перехвачена в catch, а TypeError — это название ошибки.
  2. undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение undefined как функцию.

Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.

Теперь к самим ошибкам.

Uncaught TypeError: undefined is not a function

Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected

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

var foo = undefined;
foo();

Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.

var x = document.getElementByID('foo');

Несуществующие свойства объекта по-умолчанию имеют значение undefined, что приводит к этой ошибке.

Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.

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

Uncaught ReferenceError: Invalid left-hand side in assignment

Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’

Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.

Наиболее частый пример этой ошибки — это условие в if:

if(doSomething() = 'somevalue')

В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.

Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this.

Uncaught TypeError: Converting circular structure to JSON

Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported

Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify.

var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);

Так как a и b в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.

Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.

Unexpected token ;

Связанные ошибки: Expected ), missing ) after argument list

Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.

Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected {” или что-то еще.

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

Ошибка с [ ] { } ( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.

Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.

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

Uncaught SyntaxError: Unexpected token ILLEGAL

Связанные ошибки: Unterminated String Literal, Invalid Line Terminator

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

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

Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference

Попытка прочитать null или undefined так, как будто это объект. Например:

var someVal = null;
console.log(someVal.foo);

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

Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference

Попытка записать null или undefined так, как будто это объект. Например:

var someVal = null;
someVal.foo = 1;

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

Uncaught RangeError: Maximum call stack size exceeded

Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow

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

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

Uncaught URIError: URI malformed

Связанные ошибки: URIError: malformed URI sequence

Вызвано некорректным вызовом decodeURIComponent.

Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.

XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url

Эта проблема всегда связана с использованием XMLHttpRequest.

Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Связанные ошибки: InvalidStateError, DOMException code 11

Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest при попытке вызвать на нём функции до его готовности.

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Some-Header', 'val');

В данном случае вы получите ошибку потому, что функция setRequestHeader может быть вызвана только после вызова xhr.open.

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

Заключение

JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.

Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.

P.S. Этот перевод можно улучшить, отправив PR здесь.

May 10, 2021

When writing code, we can expect a wide range of errors to happen. We should handle it by writing our code with that in mind. Even though that’s the case, some errors might slip through the cracks. This article looks into what happens with unhandled errors both in Node.js and in the browser.

Errors in JavaScript

In web development, many situations can result in an error. In general, we could divide them into two categories.

Programmer errors

Programmer errors are caused by bugs in our code. A common example is trying to access a property of undefined.

const response = undefined;

console.log(response.data);

Uncaught TypeError: Cannot read property ‘data’ of undefined

Operational errors

We might run into operational errors even if we wrote our code correctly. They don’t represent bugs but signify that something went wrong. A good example is a user sending a request when logging in, but providing a wrong password.

If you want to learn about the very basics of managing errors, check out Handling errors in JavaScript with try…catch and finally

What happens when an exception is thrown

In JavaScript, an error is an object that we can throw to indicate that something went wrong.

class PostNotFoundException extends Error {

  constructor(postId) {

    super(`Post with id ${postId} not found`);

  }

}

async getPostById(id) {

  const post = await this.postsRepository.findOne(id);

  if (post) {

    return post;

  }

  throw new PostNotFoundException(id);

}

The above snippet is based on the code from the API with NestJS series.

A crucial thing to understand is how JavaScript reacts to exceptions being thrown. First, it stops the execution of the code. Then, it moves up through the call stack of our functions, looking for the closest
try...catch block.

function divide(firstNumber, secondNumber) {

  if (secondNumber === 0) {

    throw Error(«You can’t divide by zero»);

  }

  return firstNumber / secondNumber;

}

try {

  divide(5, 0);

  console.log(‘This console.log will not run’);

} catch(exception) {

  console.log(‘An exception has been caught’);

}

Above, because the
divide function threw an error, we can see
An exception has been caught in the console.

Let’s look into the MDN documentation for the throw statement:

If no
catch block exists among caller functions, the program will terminate.

There is quite a bit more to it, though. When there is an uncaught error in the browser, it aborts processing the current script or a file. When this happens, the
window object emits the error event. We can listen to it with
addEventListener.

window.addEventListener(‘error’, () => {

  console.log(‘An uncaught error happened’);

});

A legacy way to listen for the error event is to use
window.onerror.

If we attempt to try the above code out, we might run into an issue. The above event does not fire for errors originated from the Developer Tools console. This applies both to Chrome and Firefox.

Listening to the error event allows us to create a last-resort error handling. For example, we could implement a logic that redirects the user to a page that informs that an unexpected error happened.

React embraces this approach with error boundaries. If you want to know more, check out Bug-proofing our application with Error Boundaries and the Strict Mode

We can access the error event in the listener. Aside from accessing its properties, we can call the
preventDefault() method. Doing so causes the error not to be seen in the console.

window.addEventListener(‘error’, (event) => {

  // An uncaught error happened. It will not be logged in the console.

  event.preventDefault();

});

If we throw an error in the above listener, it does not emit the error event. Thanks to that, the JavaScript engine avoids infinite recursion.

Uncaught errors in promises

We should also implement error handling for our promises.

fetch(‘https://site-does-not-exist.js’);

When we don’t catch the above promise rejection, we can expect the error to appear in the console.

Uncaught (in promise) TypeError: Failed to fetch

When this happens, the
window object emits the
unhandledrejection event. We can access the PromiseRejectionEvent and prevent the error from appearing in the console.

window.addEventListener(‘unhandledrejection’, (event) => {

  // preventing the rejection from appearing in the console

  event.preventDefault();

});

A legacy way of attach a listener to this event is to use
window.onunhandledrejection.

There are some edge cases that we should know about. Let’s consider the code below:

const request = fetch(‘https://site-does-not-exist.js’);

request.then(() => console.log(‘Resource fetched’));

request.catch(() => console.log(‘Something went wrong’));

Something went wrong
Uncaught (in promise) TypeError: Failed to fetch

Above, we can see that error appears to be uncaught even though we’ve used the
catch function. To understand this, let’s look closer into the then function. It accepts two arguments: a function called when the promise resolves, and the callback used when the promise is rejected. If we don’t explicitly provide the rejection callback, JavaScript does the following:

const request = fetch(‘https://site-does-not-exist.js’);

request.then(

  () => console.log(‘Resource fetched’),

  (error) => {

    throw error;

  }

);

request.catch(() => console.log(‘Something went wrong’));

We don’t catch the error thrown in the
then callback, and therefore, it appears as uncaught in the console. This issue does not appear if we chain the
then and
catch functions.

const request = fetch(‘https://site-does-not-exist.js’);

request

  .then(() => console.log(‘Resource fetched’))

  .catch(() => console.log(‘Something went wrong’));

Uncaught errors in Node.js

By default, causing an uncaught exception in Node.js results in printing the stack trace and exiting the process with code
1. When a process returns a non-zero code, it signifies an error.

throw new Error(‘Oops!’);

/home/marcin/Documents/Projects/errors/index.js:1

throw new Error(‘Oops!’);

^

Error: Oops!

    at Object.<anonymous> (/home/marcin/Documents/Projects/errors/index.js:1:7)

    at Module._compile (internal/modules/cjs/loader.js:1137:30)

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)

    at Module.load (internal/modules/cjs/loader.js:985:32)

    at Function.Module._load (internal/modules/cjs/loader.js:878:14)

    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)

    at internal/main/run_main_module.js:17:47

With Node.js, we don’t have the
window object. Even though that’s the case, there are some events related to uncaught exceptions.

By listening to the
uncaughtException error, we can alter the default behavior. When we do that, Node.js no longer returns code
1 but still terminates the process. We can restore the exit code through the
process.exitCode property.

If we want to listen for uncaught exceptions, but we don’t want to alter the default behavior, we can listen to the
uncaughtExceptionMonitor event instead.

process.on(‘uncaughtException’, (error) => {

  console.log(‘Uncaught exception happened’, error);

  process.exitCode = 1;

});

throw new Error(‘Oops!’);

We can also use
process.setUncaughtExceptionCaptureCallback to attach the above listener.

Although we could restart the process within the above listener, Node.js documentation strongly advises against it. The
uncaughtException listener is a place to perform the synchronous cleanup of allocated resources, such as files. It is not recommended to resume operation after the
uncaughtException event was emitted.

If we want to restart a crashed application more reliably, the official documentation suggests using an external monitor. An example of such is PM2.

Uncaught errors in promises

The topic of unhandled promise rejections in Node.js is somewhat tricky. This is because the default behavior changed across the Node.js versions.

const fs = require(‘fs’);

const util = require(‘util’);

const readFile = util.promisify(fs.readFile);

readFile(‘./non-existent-file.txt’)

  .then((content) => console.log(content));

Above, I use the
promisify function to work with promises instead of callbacks. If you want to know more about the file system module, check out Node.js TypeScript #1. Modules, process arguments, basics of the File System

When running the above code with Node.js version previous to 15, we can see the following:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This means that the process is not terminated. This behavior has been changed in Node.js 15, and the
unhandledrejections flag is now set to
throw by default. Because of that, running into an unhandled promise rejection terminates the process if we don’t listen to the
unhandledRejection event.

We can still set
unhandledrejections to
warn if we need the previous behavior.

const fs = require(‘fs’);

const util = require(‘util’);

const readFile = util.promisify(fs.readFile);

process.on(‘unhandledRejection’, (reason, promise) => {

  console.log(‘Unhandled Rejection at:’, promise, ‘reason:’, reason);

});

readFile(‘./non-existent-file.txt’);

Node.js emits the
unhandledRejection event every time a promise is rejected without error handling. By listening to it, we can keep track of rejected promises and implement logging, for example.

If we set
unhandledrejections to
strict, our process terminates on uncaught promise rejections even if we listen to the
unhandledRejection event.

Summary

In this article, we’ve looked into uncaught errors in JavaScript. It turns out, the browsers and Node.js handle it differently. A topic worth looking into more was unhandled promise rejections. The behavior differs not only between browsers and Node.js but also across different Node.js versions. All this knowledge can come in handy when debugging and building logging functionalities.

Sergye

1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

1

26.10.2018, 19:02. Показов 9353. Ответов 16

Метки нет (Все метки)


Всем доброго дня, не могу понять почему не работает (((

есть папочки
— install
—core
—installTables.php
—config
indexInstall.php

————
файл indexInstall.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use installcoreInstallTables;
 
spl_autoload_register(function ($class_name) {
 
    $path = str_replace('\', '/', $class_name.'.php');
    echo $path; //ПИШЕТ install/core/InstallTables.php
    if(file_exists($path)){
        require $path;
    }
 
});
 
$install = new InstallTables();
$install->run();

——————-

————
Файл installTables.php

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace installcore;
 
class InstallTables {
 
    public $tables; 
 
 
 
    public function __construct(){
        $this->tables = require 'install/config/tables.php'; //
 
        foreach ($this->tables as $val) {
            echo $val;
        }
    }
 
    public function run(){
        echo 'Тут я запускаюсь';
    }
}

————-

Пишет ошибку
PHP Fatal error: Uncaught Error: Class
Uncaught Error: Class ‘installcoreInstallTables’ not found in

Заранее спасибо!!!!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

26.10.2018, 19:29

2

Сделал всё как вы описали и никаких ошибок, у меня всё работает.

Цитата
Сообщение от Sergye
Посмотреть сообщение

echo $path; //ПИШЕТ install/core/InstallTables.php

Не используйте относительные пути. Лучше __DIR__ . '/' . $path;



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 19:32

 [ТС]

3

А где именно это прописать?



0



Jodah

Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

26.10.2018, 19:35

4

Sergye,

PHP
1
$path = __DIR__ . '/' . str_replace('\', '/', $class_name.'.php');



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 19:41

 [ТС]

5

Теперь пишет полный путь)))) но не пишет данные из методово класса

Сама ошибка
Uncaught Error: Class ‘installcoreInstallTables’

PHP Fatal error: Uncaught Error: Class ‘installcoreInstallTables’ not found in /home/…../install/indexInstall.php:19
Stack trace:
#0 {main}
thrown in /home/…./install/indexInstall.php on line 19

Попробывал на чистом проекте все то же смаое….



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 19:45

 [ТС]

6

вот папочки

Изображения

 



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 19:50

 [ТС]

7

При таком варианте
$path = __DIR__ . ‘/’ . str_replace(‘\’, ‘/’, $class_name.’.php’);
задваивает папку «insstall»



0



2030 / 1114 / 566

Регистрация: 23.08.2015

Сообщений: 2,836

26.10.2018, 19:54

8

Sergye, а вы не думали использовать composer?



0



Jodah

Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

26.10.2018, 20:03

9

Цитата
Сообщение от Sergye
Посмотреть сообщение

задваивает папку «insstall»

Точно. Из первого сообщения показалось, что файл InstallTables.php находится в корне.

Sergye, сделайте так:

PHP
1
var_dump(file_exists($path));

Если выведет false, значит что-то не так с путями, проверьте ещё раз иерархию папок.

Добавлено через 3 минуты
Sergye, с текущей иерархией должно работать так:

PHP
1
$path = realpath(__DIR__ . '/..') . '/' . str_replace('\', '/', $class_name.'.php');



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 20:10

 [ТС]

10

да ответ install/core/InstallTables.phpbool(false)

Что именно с папками не так?

Добавлено через 2 минуты
а вот так работает

$path = realpath(__DIR__ . ‘/..’) . ‘/’ . str_replace(‘\’, ‘/’, $class_name.’.php’);

Добавлено через 3 минуты
Может кто объеснит почему не работает??? в другой части кода ведь работает (в другом каталоге)))))



0



Эксперт PHP

3802 / 3160 / 1326

Регистрация: 01.08.2012

Сообщений: 10,717

26.10.2018, 20:16

11

Sergye, потому что вы используете относительный путь, он меняется в зависимости от местонахождения подключающего файла. А __DIR__ ссылается на путь самого файла indexInstall, который всегда одинаковый.



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 20:21

 [ТС]

12

так файлы лежат в одном и том же месте и место положения не меняют! или я что то не понимаю?

Добавлено через 1 минуту
хм….перенес фал в самы корень прокта и запусти…все заработало!



0



2030 / 1114 / 566

Регистрация: 23.08.2015

Сообщений: 2,836

26.10.2018, 20:24

13

Sergye, indexInstall.php у вас находится в папке install, отсюда и __DIR__ дает путь к этой папке. Вместо __DIR__ можно использовать $_SERVER[«DOCUMENT_ROOT»]. Я бы автолоадер вынес в отдельный файл.



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 20:39

 [ТС]

14

Поделитесь примером как вытащить в отдельный файл (пример бы)

С проблемой боле мене разобрался. Всем спасибо!



0



2030 / 1114 / 566

Регистрация: 23.08.2015

Сообщений: 2,836

26.10.2018, 21:01

15

Sergye, что там пример писать, создаете файл autoloader.php, там пишете свою функцию spl_autoload_register. И подключаете через require_once

Добавлено через 9 минут
Sergye, Но вообще я бы все-таки советовал использовать composer там уже есть автолоадер. composer упрощает жизнь, тем более что сейчас без него довольно затруднительно использовать современные библиотеки, которые непременно вам понадобятся)



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

26.10.2018, 21:13

 [ТС]

16

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



0



1 / 1 / 0

Регистрация: 29.05.2016

Сообщений: 37

27.10.2018, 12:25

 [ТС]

17

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

что там пример писать, создаете файл autoloader.php, там пишете свою функцию spl_autoload_register. И подключаете через require_once



0



Понравилась статья? Поделить с друзьями:
  • Error unable to load root certificates unable to parse bytes as pem block
  • Error unable to load restore ramdisk
  • Error unable to load library dbdata dll ок
  • Error unable to load info from any available system nvidia settings
  • Error unable to load indexed mesh