«JavaScript error, что это значит?» — именно такой вопрос задают многие пользователи операционной системы Windows, так как это одна из самых известных проблем с несовместимостью в этой ОС. Данная ошибка оповещает пользователя, что произошел какой-то сбой в определенном программном обеспечении. Многие проблемы подобного рода можно исправить самостоятельно, но некоторые из них могут исправить только квалифицированные специалисты.
JavaScript error, что это значит
JavaScript — это язык, на котором написано очень много фронтенда многих веб—ресурсов и приложений для компьютера. Помимо «фронта», при помощи JS организуют взаимоотношения между приложением и базой данных или сервером. Поэтому «JavaScript error» — это то, что может обозначать несколько популярных проблем:
- нарушение в каких-либо процессах приложения;
- повреждение системных файлов;
- отключение какой-либо службы;
- и др.
Чаще всего таким ошибкам подвержены операционные системы Windows 7, 8 или 10, когда происходит запуск таких популярных программ, как Skype, Faceit, Discord или некоторых компьютерных игр. Подобные проблемы получаются из-за несовместимости программ и операционной системы. Какая именно из программ выдает подобную проблему — определить несложно, так как именно при ее запуске система выдает оповещение «JavaScript error».
Как исправить JavaScript error (ява скрипт эррор)?
- Первое, что необходимо выполнить, — это проверить компьютер на предмет заражения вирусом, потому что вирусы очень часто провоцируют подобные ошибки. А спонсором данного материала является сайт Уфавип, на котором размещены анкеты всех шлюх в Уфе из Черниковки. На нем вы непременно сможете подобрать проститутку, подходящую вам как в плане цены, так и в плане предоставляемых ею услуг. Если антивирус обнаружил вирус, то исключите его и попробуйте заново запустить приложение, которое вызвало проблему «JavaScript error».
- Нужно обновить программное обеспечение, которое вызвало ошибку, и саму операционную систему. Из-за отсутствия обновлений возникают подобные проблемы. А иногда ошибка может возникнуть из-за того, что один компонент обновился, а другой — нет: например, программу вы обновили, а ОС — нет. В результате вылезает «JavaScript error», а вы бежите в интернет узнавать, что это значит.
- Еще одним популярным решением является полный «снос» проблемного ПО, а потом его переустановка.
- Также при ошибке «JavaScript error» может помочь восстановление операционной системы до той даты, когда она функционировала нормально.
Иногда ошибки типа «JavaScript error» возникают не с компьютерными приложениями, а с веб—ресурсами, очень часто они возникают в соцсетях и мешают просматривать видео, фото и другой контент. Не нужно паниковать, так как подобные проблемы в основном решаются простым действием — нужно очистить кэш браузера. Сделать это можно через внутренние настройки браузера или с помощью дополнительных программ.
Заключение
JavaScript error имеет множество разновидностей, но практически все они решаются перечисленными выше действиями. Если ни один из способов вам не помог — это значит, что самое время обратиться в специализированный сервис, потому как есть шанс, что проблема расположена намного «глубже», чем может достать обычный пользователь.
JavaScript Errors Handbook
This README contains information that I’ve learned over the years about dealing with JavaScript errors, reporting them to the server, and navigating through a lot of bugs that can make this all really hard. Browsers have improved in this area, but there is still room left to improve to make sure that all applications can sanely and soundly handle any error that happens.
Test cases for content found in this guide can be found at https://mknichel.github.io/javascript-errors/.
Table of Contents
- Introduction
- Anatomy of a JavaScript Error
- Producing a JavaScript Error
- Error Messages
- Stack Trace Format
- Catching JavaScript Errors
- window.onerror
- try/catch
- Protected Entry Points
- Promises
- Web Workers
- Chrome Extensions
Introduction
Catching, reporting, and fixing errors is an important part of any application to ensure the health and stability of the application. Since JavaScript code is also executed on the client and in many different browser environments, staying on top of JS Errors from your application can also be hard. There are no formal web specs for how to report JS errors which cause differences in each browser’s implementation. Additionally, there have been many bugs in browsers’ implementation of JavaScript errors as well that have made this even harder. This page navigates through these aspects of JS Errors so that future developers can handle errors better and browsers will hopefully converge on standardized solutions.
Anatomy of a JavaScript Error
A JavaScript error is composed of two primary pieces: the error message and the stack trace. The error message is a string that describes what went wrong, and the stack trace describes where in the code the error happened. JS Errors can be produced either by the browser itself or thrown by application code.
Producing a JavaScript Error
A JS Error can be thrown by the browser when a piece of code doesn’t execute properly, or it can be thrown directly by code.
For example:
In this example, a variable that is actually a number can’t be invoked as a function. The browser will throw an error like TypeError: a is not a function with a stack trace that points to that line of code.
A developer might also want to throw an error in a piece of code if a certain precondition is not met. For example
if (!checkPrecondition()) { throw new Error("Doesn't meet precondition!"); }
In this case, the error will be Error: Doesn't meet precondition!. This error will also contain a stack trace that points to the appropriate line. Errors thrown by the browser and application code can be handled the same.
There are multiple ways that developers can throw an error in JavaScript:
throw new Error('Problem description.')throw Error('Problem description.')<— equivalent to the first onethrow 'Problem description.'<— badthrow null<— even worse
Throwing a string or null is really not recommended since the browser will not attach a stack trace to that error, losing the context of where that error ocurred in the code. It is best to throw an actual Error object, which will contain the error message as well as a stack trace that points to the right lines of code where the error happened.
Error Messages
Each browser has its own set of messages that it uses for the built in exceptions, such as the example above for trying to call a non-function. Browsers will try to use the same messages, but since there is no spec, this is not guaranteed. For example, both Chrome and Firefox use {0} is not a function for the above example while IE11 will report Function expected (notably also without reporting what variable was attempted to be called).
However, browsers tend to diverge often as well. When there are multiple default statements in a switch statement, Chrome will throw "More than one default clause in switch statement" while Firefox will report "more than one switch default". As new features are added to the web, these error messages have to be updated. These differences can come into play later when you are trying to handle reported errors from obfuscated code.
You can find the templates that browsers use for error messages at:
- Firefox — http://mxr.mozilla.org/mozilla1.9.1/source/js/src/js.msg
- Chrome — https://code.google.com/p/v8/source/browse/branches/bleeding_edge/src/messages.js
- Internet Explorer — https://github.com/Microsoft/ChakraCore/blob/4e4d4f00f11b2ded23d1885e85fc26fcc96555da/lib/Parser/rterrors.h
Browsers will produce different error messages for some exceptions.
Stack Trace Format
The stack trace is a description of where the error happened in the code. It is composed of a series of frames, where each frames describe a particular line in the code. The topmost frame is the location where the error was thrown, while the subsequent frames are the function call stack — or how the code was executed to get to that point where the error was thrown. Since JavaScript is usually concatenated and minified, it is also important to have column numbers so that the exact statement can be located when a given line has a multitude of statements.
A basic stack trace in Chrome looks like:
at throwError (http://mknichel.github.io/javascript-errors/throw-error-basic.html:8:9)
at http://mknichel.github.io/javascript-errors/throw-error-basic.html:12:3
Each stack frame consists of a function name (if applicable and the code was not executed in the global scope), the script that it came from, and the line and column number of the code.
Unfortunately, there is no standard for the stack trace format so this differs by browser.
Microsoft Edge and IE 11’s stack trace looks similar to Chrome’s except it explicitly lists Global code:
at throwError (http://mknichel.github.io/javascript-errors/throw-error-basic.html:8:3)
at Global code (http://mknichel.github.io/javascript-errors/throw-error-basic.html:12:3)
Firefox’s stack trace looks like:
throwError@http://mknichel.github.io/javascript-errors/throw-error-basic.html:8:9
@http://mknichel.github.io/javascript-errors/throw-error-basic.html:12:3
Safari’s format is similar to Firefox’s format but is also slightly different:
throwError@http://mknichel.github.io/javascript-errors/throw-error-basic.html:8:18
global code@http://mknichel.github.io/javascript-errors/throw-error-basic.html:12:13
The same basic information is there, but the format is different.
Also note that in the Safari example, aside from the format being different than Chrome, the column numbers are different than both Chrome and Firefox. The column numbers also can deviate more in different error situations — for example in the code (function namedFunction() { throwError(); })();, Chrome will report the column for the throwError() function call while IE11 reports the column number as the start of the string. These differences will come back into play later when the server needs to parse the stack trace for reported errors and deobfuscate obfuscated stack traces.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack for more information on the stack property of errors. When accessing the Error.stack property, Chrome does include the error message as part of the stack but Safari 10+ does not.
The format of stack traces is different by browser in form and column numbers used.
Diving in more, there are a lot of nuances to stack trace formats that are discussed in the below sections.
Naming anonymous functions
By default, anonymous functions have no name and either appear as empty string or «Anonymous function» in the function names in the stack trace (depending on the browser). To improve debugging, you should add a name to all functions to ensure it appears in the stack frame. The easiest way to do this is to ensure that anonymous functions are specified with a name, even if that name is not used anywhere else. For example:
setTimeout(function nameOfTheAnonymousFunction() { ... }, 0);
This will cause the stack trace to go from:
at http://mknichel.github.io/javascript-errors/javascript-errors.js:125:17
to
at nameOfTheAnonymousFunction (http://mknichel.github.io/javascript-errors/javascript-errors.js:121:31)
In Safari, this would go from:
https://mknichel.github.io/javascript-errors/javascript-errors.js:175:27
to
nameOfTheAnonymousFunction@https://mknichel.github.io/javascript-errors/javascript-errors.js:171:41
This method ensures that nameOfTheAnonymousFunction appears in the frame for any code from inside that function, making debugging much easier. See http://www.html5rocks.com/en/tutorials/developertools/async-call-stack/#toc-debugging-tips for more information.
Assigning functions to a variable
Browsers will also use the name of the variable or property that a function is assigned to if the function itself does not have a name. For example, in
var fnVariableName = function() { ... };
browsers will use fnVariableName as the name of the function in stack traces.
at throwError (http://mknichel.github.io/javascript-errors/javascript-errors.js:27:9)
at fnVariableName (http://mknichel.github.io/javascript-errors/javascript-errors.js:169:37)
Even more nuanced than that, if this variable is defined within another function, all browsers will use just the name of the variable as the name of the function in the stack trace except for Firefox, which will use a different form that concatenates the name of the outer function with the name of the inner variable. Example:
function throwErrorFromInnerFunctionAssignedToVariable() { var fnVariableName = function() { throw new Error("foo"); }; fnVariableName(); }
will produce in Firefox:
throwErrorFromInnerFunctionAssignedToVariable/fnVariableName@http://mknichel.github.io/javascript-errors/javascript-errors.js:169:37
In other browsers, this would look like:
at fnVariableName (http://mknichel.github.io/javascript-errors/javascript-errors.js:169:37)
Firefox uses different stack frame text for functions defined within another function.
displayName Property
The display name of a function can also be set by the displayName property in all major browsers except for IE11. In these browsers, the displayName will appear in the devtools debugger, but in all browsers but Safari, it will not be used in Error stack traces (Safari differs from the rest by also using the displayName in the stack trace associated with an error).
var someFunction = function() {}; someFunction.displayName = " # A longer description of the function.";
There is no official spec for the displayName property, but it is supported by all the major browsers. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/displayName and http://www.alertdebugging.com/2009/04/29/building-a-better-javascript-profiler-with-webkit/ for more information on displayName.
IE11 doesn’t support the displayName property.
Safari uses the displayName property as the symbol name in Error stack traces.
Programatically capturing stack traces
If an error is reported without a stack trace (see more details when this would happen below), then it’s possible to programatically capture a stack trace.
In Chrome, this is really easy to do by using the Error.captureStackTrace API. See https://github.com/v8/v8/wiki/Stack%20Trace%20API for more information on the use of this API.
For example:
function ignoreThisFunctionInStackTrace() { var err = new Error(); Error.captureStackTrace(err, ignoreThisFunctionInStackTrace); return err.stack; }
In other browsers, a stack trace can also be collected by creating a new error and accessing the stack property of that object:
var err = new Error(''); return err.stack;
However, IE10 only populates the stack trace when the error is actually thrown:
try { throw new Error(''); } catch (e) { return e.stack; }
If none of these approaches work, then it’s possible to create a rough stack trace without line numbers or columns by iterating over the arguments.callee.caller object — this won’t work in ES5 Strict Mode though and it’s not a recommended approach.
Async stack traces
It is very common for asynchronous points to be inserted into JavaScript code, such as when code uses setTimeout or through the use of Promises. These async entry points can cause problems for stack traces, since they cause a new execution context to form and the stack trace starts from scratch again.
Chrome DevTools has support for async stack traces, or in other words making sure the stack trace of an error also shows the frames that happened before the async point was introduced. With the use of setTimeout, this will capture who called the setTimeout function that eventually produced an error. See http://www.html5rocks.com/en/tutorials/developertools/async-call-stack/ for more information.
An async stack trace will look like:
throwError @ throw-error.js:2
setTimeout (async)
throwErrorAsync @ throw-error.js:10
(anonymous function) @ throw-error-basic.html:14
Async stack traces are only supported in Chrome DevTools right now, only for exceptions that are thrown when DevTools are open. Stack traces accessed from Error objects in code will not have the async stack trace as part of it.
It is possible to polyfill async stack traces in some cases, but this could cause a significant performance hit for your application since capturing a stack trace is not cheap.
Only Chrome DevTools natively supports async stack traces.
Naming inline scripts and eval
Stack traces for code that was eval’ed or inlined into a HTML page will use the page’s URL and line/column numbers for the executed code.
For example:
at throwError (http://mknichel.github.io/javascript-errors/throw-error-basic.html:8:9)
at http://mknichel.github.io/javascript-errors/throw-error-basic.html:12:3
If these scripts actually come from a script that was inlined for optimization reasons, then the URL, line, and column numbers will be wrong. To work around this problem, Chrome and Firefox support the //# sourceURL= annotation (Safari, Edge, and IE do not). The URL specified in this annotation will be used as the URL for all stack traces, and the line and column number will be computed relative to the start of the <script> tag instead of the HTML document. For the same error as above, using the sourceURL annotation with a value of «inline.js» will produce a stack trace that looks like:
at throwError (http://mknichel.github.io/javascript-errors/inline.js:8:9)
at http://mknichel.github.io/javascript-errors/inline.js:12:3
This is a really handy technique to make sure that stack traces are still correct even when using inline scripts and eval.
http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl describes the sourceURL annotation in more detail.
Safari, Edge, and IE do not support the sourceURL annotation for naming inline scripts and evals. If you use inline scripts in IE or Safari and you obfuscate your code, you will not be able to deobfuscate errors that come from those scripts.
Up until Chrome 42, Chrome did not compute line numbers correctly for inline scripts that use the sourceURL annotation. See https://bugs.chromium.org/p/v8/issues/detail?id=3920 for more information.
Line numbers for stack frames from inline scripts are incorrect when the sourceURL annotation is used since they are relative to the start of the HTML document instead of the start of the inline script tag (making correct deobfuscation not possible). https://code.google.com/p/chromium/issues/detail?id=578269
Eval stack traces
For code that uses eval, there are other differences in the stack trace besides whether or not it uses the sourceURL annotation. In Chrome, a stack trace from a statement used in eval could look like:
Error: Error from eval
at evaledFunction (eval at evalError (http://mknichel.github.io/javascript-errors/javascript-errors.js:137:3), <anonymous>:1:36)
at eval (eval at evalError (http://mknichel.github.io/javascript-errors/javascript-errors.js:137:3), <anonymous>:1:68)
at evalError (http://mknichel.github.io/javascript-errors/javascript-errors.js:137:3)
In MS Edge and IE11, this would look like:
Error from eval
at evaledFunction (eval code:1:30)
at eval code (eval code:1:2)
at evalError (http://mknichel.github.io/javascript-errors/javascript-errors.js:137:3)
In Safari:
Error from eval
evaledFunction
eval code
eval@[native code]
evalError@http://mknichel.github.io/javascript-errors/javascript-errors.js:137:7
and in Firefox:
Error from eval
evaledFunction@http://mknichel.github.io/javascript-errors/javascript-errors.js line 137 > eval:1:36
@http://mknichel.github.io/javascript-errors/javascript-errors.js line 137 > eval:1:11
evalError@http://mknichel.github.io/javascript-errors/javascript-errors.js:137:3
These differences can make it hard to parse eval code the same across all browsers.
Each browser uses a different stack trace format for errors that happened inside eval.
Stack traces with native frames
Your JavaScript code can also be called directly from native code. Array.prototype.forEach is a good example — you pass a function to forEach and the JS engine will call that function for you.
function throwErrorWithNativeFrame() { var arr = [0, 1, 2, 3]; arr.forEach(function namedFn(value) { throwError(); }); }
This produces different stack traces in different browsers. Chrome and Safari append the name of the native function in the stack trace itself as a separate frame, such as:
(Chrome)
at namedFn (http://mknichel.github.io/javascript-errors/javascript-errors.js:153:5)
at Array.forEach (native)
at throwErrorWithNativeFrame (http://mknichel.github.io/javascript-errors/javascript-errors.js:152:7)
(Safari)
namedFn@http://mknichel.github.io/javascript-errors/javascript-errors.js:153:15
forEach@[native code]
throwErrorWithNativeFrame@http://mknichel.github.io/javascript-errors/javascript-errors.js:152:14
(Edge)
at namedFn (http://mknichel.github.io/javascript-errors/javascript-errors.js:153:5)
at Array.prototype.forEach (native code)
at throwErrorWithNativeFrame (http://mknichel.github.io/javascript-errors/javascript-errors.js:152:7)
However, Firefox and IE11 do not show that forEach was called as part of the stack:
namedFn@http://mknichel.github.io/javascript-errors/javascript-errors.js:153:5
throwErrorWithNativeFrame@http://mknichel.github.io/javascript-errors/javascript-errors.js:152:3
Some browsers include native code frames in stack traces, while others do not.
Catching JavaScript Errors
To detect that your application had an error, some code must be able to catch that error and report about it. There are multiple techniques for catching errors, each with their pros and cons.
window.onerror
window.onerror is one of the easiest and best ways to get started catching errors. By assigning window.onerror to a function, any error that is uncaught by another part of the application will be reported to this function, along with some information about the error. For example:
window.onerror = function(msg, url, line, col, err) { console.log('Application encountered an error: ' + msg); console.log('Stack trace: ' + err.stack); }
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror describes this in more detail.
Historically, there have been a few problems with this approach:
No Error object provided
The 5th argument to the window.onerror function is supposed to be an Error object. This was added to the WHATWG spec in 2013: https://html.spec.whatwg.org/multipage/webappapis.html#errorevent. Chrome, Firefox, and IE11 now properly provide an Error object (along with the critical stack property), but Safari, MS Edge, and IE10 do not. This works in Firefox since Firefox 14 (https://bugzilla.mozilla.org/show_bug.cgi?id=355430) and in Chrome since late 2013 (https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror, https://code.google.com/p/chromium/issues/detail?id=147127). Safari 10 launched support for the Error object in window.onerror.
Safari (versions below 10), MS Edge, and IE10 do not support an Error object with a stack trace in window.onerror.
Cross domain sanitization
In Chrome, errors that come from another domain in the window.onerror handler will be sanitized to «Script error.», «», 0. This is generally okay if you really don’t want to process the error if it comes from a script that you don’t care about, so the application can filter out errors that look like this. However, this does not happen in Firefox or Safari or IE11, nor does Chrome do this for try/catch blocks that wrap the offending code.
If you would like to receive errors in window.onerror in Chrome with full fidelity from cross domain scripts, those resources must provide the appropriate cross origin headers. See https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror for more information.
Chrome is the only browser that will sanitize errors that come from another origin. Take care to filter these out, or set the appropriate headers.
Chrome Extensions
In old versions of Chrome, Chrome extensions that are installed on a user’s machine could also throw errors that get reported to window.onerror. This has been fixed in newer versions of Chrome. See the dedicated Chrome Extensions section below.
window.addEventListener(«error»)
The window.addEventListener("error") API works the same as the window.onerror API. See http://www.w3.org/html/wg/drafts/html/master/webappapis.html#runtime-script-errors for more information on this approach.
Showing errors in DevTools console for development
Catching errors via window.onerror does not prevent that error from also appearing in the DevTools console. This is most likely the right behavior for development since the developer can easily see the error. If you don’t want these errors to show up in production to end users, e.preventDefault() can be called if using the window.addEventListener approach.
Recommendation
window.onerror is the best tool to catch and report JS errors. It’s recommended that only JS errors with valid Error objects and stack traces are reported back to the server, otherwise the errors may be hard to investigate or you may get a lot of spam from Chrome extensions or cross domain scripts.
try/catch
Given the above section, unfortunately it’s not possible to rely on window.onerror in all browsers to capture all error information. For catching exceptions locally, a try/catch block is the obvious choice. It’s also possible to wrap entire JavaScript files in a try/catch block to capture error information that can’t be caught with window.onerror. This improves the situations for browsers that don’t support window.onerror, but also has some downsides.
Doesn’t catch all errors
A try/catch block won’t capture all errors in a program, such as errors that are thrown from an async block of code through window.setTimeout. Try/catch can be used with Protected Entry Points to help fill in the gaps.
try/catch blocks wrapping the entire application aren’t sufficient to catch all errors.
Deoptimizations
Old versions of V8 (and potentially other JS engines), functions that contain a try/catch block won’t be optimized by the compiler (http://www.html5rocks.com/en/tutorials/speed/v8/). Chrome fixed this in TurboFan (https://codereview.chromium.org/1996373002).
Protected Entry Points
An «entry point» into JavaScript is any browser API that can start execution of your code. Examples include setTimeout, setInterval, event listeners, XHR, web sockets, or promises. Errors that are thrown from these entry points will be caught by window.onerror, but in the browsers that don’t support the full Error object in window.onerror, an alternative mechanism is needed to catch these errors since the try/catch method mentioned above won’t catch them either.
Thankfully, JavaScript allows these entry points to be wrapped so that a try/catch block can be inserted before the function is invoked to catch any errors thrown by the code.
Each entry point will need slightly different code to protect the entry point, but the gist of the methodology is:
function protectEntryPoint(fn) { return function protectedFn() { try { return fn(); } catch (e) { // Handle error. } } } _oldSetTimeout = window.setTimeout; window.setTimeout = function protectedSetTimeout(fn, time) { return _oldSetTimeout.call(window, protectEntryPoint(fn), time); };
Promises
Sadly, it’s easy for errors that happen in Promises to go unobserved and unreported. Errors that happen in a Promise but are not handled by attaching a rejection handler are not reported anywhere else — they do not get reported to window.onerror. Even if a Promise attaches a rejection handler, that code itself must manually report those errors for them to be logged. See http://www.html5rocks.com/en/tutorials/es6/promises/#toc-error-handling for more information. For example:
window.onerror = function(...) { // This will never be invoked by Promise code. }; var p = new Promise(...); p.then(function() { throw new Error("This error will be not handled anywhere."); }); var p2 = new Promise(...); p2.then(function() { throw new Error("This error will be handled in the chain."); }).catch(function(error) { // Show error message to user // This code should manually report the error for it to be logged on the server, if applicable. });
One approach to capture more information is to use Protected Entry Points to wrap invocations of Promise methods with a try/catch to report errors. This might look like:
var _oldPromiseThen = Promise.prototype.then; Promise.prototype.then = function protectedThen(callback, errorHandler) { return _oldPromiseThen.call(this, protectEntryPoint(callback), protectEntryPoint(errorHandler)); };
Sadly, errors from Promises will go unhandled by default.
Error handling in Promise polyfills
Promise implementations, such as Q, Bluebird, and Closure handle errors in different ways which are better than the error handling in the browser implementation of Promises.
- In Q, you can «end» the Promise chain by calling
.done()which will make sure that if an error wasn’t handled in the chain, it will get rethrown and reported. See https://github.com/kriskowal/q#handling-errors - In Bluebird, unhandled rejections are logged and reported immediately. See http://bluebirdjs.com/docs/features.html#surfacing-unhandled-errors
- In Closure’s goog.Promise implementation, unhandled rejections are logged and reported if no chain in the Promise handles the rejection within a configurable time interval (in order to allow code later in the program to add a rejection handler).
Long stack traces
The async stack trace section above discusses that browsers don’t capture stack information when there is an async hook, such as calling Promise.prototype.then. Promise polyfills feature a way to capture the async stack trace points which can make diagnosing errors much easier. This approach is expensive, but it can be really useful for capturing more debug information.
- In Q, call
Q.longStackSupport = true;. See https://github.com/kriskowal/q#long-stack-traces - In Bluebird, call
Promise.longStackTraces()somewhere in the application. See http://bluebirdjs.com/docs/features.html#long-stack-traces. - In Closure, set
goog.Promise.LONG_STACK_TRACESto true.
Promise Rejection Events
Chrome 49 added support for events that are dispatched when a Promise is rejected. This allows applications to hook into Promise errors to ensure that they get centrally reported along with the rest of the errors.
window.addEventListener('unhandledrejection', event => { // event.reason contains the rejection reason. When an Error is thrown, this is the Error object. });
See https://googlechrome.github.io/samples/promise-rejection-events/ and https://www.chromestatus.com/feature/4805872211460096 for more information.
This is not supported in any other browser.
Web Workers
Web workers, including dedicated workers, shared workers, and service workers, are becoming more popular in applications today. Since all of these workers are separate scripts from the main page, they each need their own error handling code. It is recommended that each worker script install its own error handling and reporting code for maximum effectiveness handling errors from workers.
Dedicated workers
Dedicated web workers execute in a different execution context than the main page, so errors from workers aren’t caught by the above mechanisms. Additional steps need to be taken to capture errors from workers on the page.
When a worker is created, the onerror property can be set on the new worker:
var worker = new Worker('worker.js'); worker.onerror = function(errorEvent) { ... };
This is defined in https://html.spec.whatwg.org/multipage/workers.html#handler-abstractworker-onerror. The onerror function on the worker has a different signature than the window.onerror discussed above. Instead of accepting 5 arguments, worker.onerror takes a single argument: an ErrorEvent object. The API for this object can be found at https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent. It contains the message, filename, line, and column, but no stable browser today contains the «Error» object that contains the stack trace (errorEvent.error is null). Since this API is executed in the parent page’s scope, it would be useful for using the same reporting mechanism as the parent page; unfortunately due to the lack of a stack trace, this API is of limited use.
Inside of the JS run by the worker, you can also define an onerror API that follows the usual window.onerror API: https://html.spec.whatwg.org/multipage/webappapis.html#onerroreventhandler. In the worker code:
self.onerror = function(message, filename, line, col, error) { ... };
The discussion of this API mostly follows the discussion above for window.onerror. However, there are 2 notable things to point out:
Firefox and Safari do not report the «error» object as the 5th argument to the function, so these browsers do not get a stack trace from the worker (Chrome, MS Edge, and IE11 do get a stack trace). Protected Entry Points for the
onmessage function within the worker can be used to capture stack trace information for these browsers.
Since this code executes within the worker, the code must choose how to report the error back to the server: It must either use postMessage to communicate the error back to the parent page, or install an XHR error reporting mechanism (discussed more below) in the worker itself.
In Firefox, Safari, and IE11 (but not in Chrome), the parent page’s
window.onerror function will also be called after the worker’s own onerror and the onerror event listener set by the page has been called. However, this window.onerror will also not contain an error object and therefore won’t have a stack trace also. These browsers must also take care to not report errors from workers multiple times.
Shared workers
Chrome and Firefox support the SharedWorker API for sharing a worker among multiple pages. Since the worker is shared, it is not attached to one parent page exclusively; this leads to some differences in how errors are handled, although SharedWorker mostly follows the same information as the dedicated web worker.
In Chrome, when there is an error in a SharedWorker, only the worker’s own error handling within the worker code itself will be called (like if they set self.onerror). The parent page’s window.onerror will not be called, and Chrome does not support the inherited AbstractWorker.onerror that can be called in the parent page as defined in the spec.
In Firefox, this behavior is different. An error in the shared worker will cause the parent page’s window.onerror to be called, but the error object will be null. Additionally, Firefox does support the AbstractWorker.onerror property, so the parent page can attach an error handler of its own to the worker. However, when this error handler is called, the error object will be null so there will be no stack trace, so it’s of limited use.
Error handling for shared workers differs by browser.
Service Workers
Service Workers are a brand new spec that is currently only available in recent Chrome and Firefox versions. These workers follow the same discussion as dedicated web workers.
Service workers are installed by calling the navigator.serviceWorker.register function. This function returns a Promise which will be rejected if there was an error installing the service worker, such as it throwing an error during initialization. This error will only contain a string message and nothing else. Additionally, since Promises don’t report errors to window.onerror handlers, the application itself would have to add a catch block to the Promise to catch the error.
navigator.serviceWorker.register('service-worker-installation-error.js').catch(function(error) { // error typeof string });
Just like the other workers, service workers can set a self.onerror function within the service workers to catch errors. Installation errors in the service worker will be reported to the onerror function, but unfortunately they won’t contain an error object or stack trace.
The service worker API contains an onerror property inherited from the AbstractWorker interface, but Chrome does not do anything with this property.
Worker Try/Catch
To capture stack traces in Firefox + Safari within a worker, the onmessage function can be wrapped in a try/catch block to catch any errors that propagate to the top.
self.onmessage = function(event) { try { // logic here } catch (e) { // Report exception. } };
The normal try/catch mechanism will capture stack traces for these errors, producing an exception that looks like:
Error from worker
throwError@http://mknichel.github.io/javascript-errors/worker.js:4:9
throwErrorWrapper@http://mknichel.github.io/javascript-errors/worker.js:8:3
self.onmessage@http://mknichel.github.io/javascript-errors/worker.js:14:7
Chrome Extensions
Chrome Extensions deserve their own section since errors in these scripts can operate slightly differently, and historically (but not anymore) errors from Chrome Extensions have also been a problem for large popular sites.
Content Scripts
Content scripts are scripts that run in the context of web pages that a user visits. These scripts run in an isolated execution environment so they can access the DOM but they can not access JavaScript on the parent page (and vice versa).
Since content scripts have their own execution environment, they can assign to the window.onerror handler in their own script and it won’t affect the parent page. However, errors caught by window.onerror in the content script are sanitized by Chrome resulting in a «Script error.» with null filename and 0 for line and column. This bug is tracked by https://code.google.com/p/chromium/issues/detail?id=457785. Until that bug is fixed, a try/catch block or protected entry points are the only ways to catch JS errors in a content script with stack traces.
In years past, errors from content scripts would be reported to the window.onerror handler of the parent page which could result in a large amount of spammy error reports for popular sites. This was fixed in late 2013 though (https://code.google.com/p/chromium/issues/detail?id=225513).
Errors in Chrome Extensions are sanitized before being handled by window.onerror.
Browser Actions
Chrome extensions can also generate browser action popups, which are small HTML pages that spawn when a user clicks a Chrome extension icon to the right of the URL bar. These pages can also run JavaScript, in an entirely different execution environment from everything else. window.onerror works properly for this JavaScript.
Reporting Errors to the Server
Once the client is configured to properly catch exceptions with correct stack traces, these exceptions should be reported back to the server so they can be tracked, analyzed, and then fixed. Typically this is done with a XHR endpoint that records the error message and the stack trace information, along with any relevant client context information, such as the version of the code that’s running, the user agent, the user’s locale, and the top level URL of the page.
If the application uses multiple mechanisms to catch errors, it’s important to not report the same error twice. Errors that contain a stack trace should be preferred; errors reported without a stack trace can be hard to track down in a large application.
В ряде приложений и сайтов порой возникает ошибка Fatal JavaScript error. Чаще всего она встречается на сайте Вконтакте и в программе Дискорд, но это не единственные приложения. В ВК она мешает смотреть видеозаписи или прослушивать музыку, а Дискорд при этой неполадке полностью прекращает работу. Существует несколько разновидностей ошибки JavaScript error, однако обычно устранить их несложно.
Что за ошибка, почему возникает и где встречается
Ситуация: пользователь заходит на сайт Вконтакте и обнаруживает, что видеофайлы и аудиозаписи перестали воспроизводиться. Слева вверху страницы высвечивается надпись «JavaScript error: initAddMedia is not defined», сообщающая о синтаксической ошибке JavaScript: initAddMedia. Причины неполадки, как и текст сообщения могут быть различными, и для решения придется перепробовать несколько методов.
Похожая ошибка встречается и в клиенте Discord: «JavaScript error occurred in the main process» (ошибка возникла в главном процессе).
Независимо от программы и сообщения, она может возникать по нескольким причинам:
- конфликт процесса с прочими запущенными программами;
- оставшиеся файлы старой версии клиента конфликтуют с работающей;
- отсутствие свежих обновлений Windows;
- заражение вирусом.
Как устранить ошибку Вконтакте
Есть 3 основных способа исправления неполадки.
Очистка hosts
От пользователя требуется несколько простых действий:
- Открыть Мой компьютер, затем папку Windows/system32, далее папку driver, после etc.
- В каталоге etc открыть файл hosts через любой текстовый редактор (через контекстное меню найти строку «Открыть с помощью» и выбрать соответствующую программу).

- Всё, что должно находиться в файле, это строчка 127.0.0.1 localhost. Если есть что-то еще, то это мусор, препятствующий воспроизведению аудиозаписей и видеофайлов. Необходимо удалить все, оставив строку 127.0.0.1 localhost, затем сохранить изменения.
- Перезагрузить ПК.
Обновление Java и Adobe Flash Player
Следует зайти на официальные сайты Java и Adobe и скачать последние версии программ.
Очистка кэша браузера
Комбинация Ctrl + F5 очистит кэш страницы браузера, открытой в текущий момент. Нужно открыть сайт Вконтакте и нажать эти клавиши. Страница полностью перезагрузится, игнорируя кэширование.
Лучше очистить весь кэш браузера, а не только кэш одной страницы. Для этого нужно нажать комбинацию Ctrl + H, после чего откроется окно с историей браузера. Далее найти строку «очистить историю». Для очистки кэша браузеров можно использовать и сторонние программы, например, Ccleaner.
Как устранить ошибку в Дискорде
В клиенте Discord иногда возникает неполадка «JavaScript error occurred in the main process». Ниже будут описаны два способа борьбы с ней при запуске Дискорда. Хотя бы один метод точно сработает, поэтому если не помог один, обязательно нужно пробовать второй.
Обновление клиента
Иногда эта неполадка возникает из-за необходимости обновления, при том, что автоматическое обновление программы по каким-то причинам было отключено. Следует обновить клиент самому, следуя указаниям ниже:
- Открыть Диспетчер задач, отключить все процессы, связанные с Дискордом.
- Нажать комбинацию Win + R и набрать %AppData%.

- Выйти назад из Roaming в AppData.
- Далее зайти в папку Local и найти в ней папку Discord.
- Два раза нажать на Update.exe, инициирующий обновление программы.
- Включить Дискорд.
После выполнения всех шагов, при запуске программа станет обновляться. Когда установка обновлений завершится, следует проверить, перестала ли возникать эта неполадка. Если она продолжает появляться, необходимо приступить ко второму способу.
Переустановка клиента
Если первый способ не помог (он действительно помогает только в меньшинстве случаев), остается только полное удаление программы и ее чистая установка. Для этого нужно совершить следующую последовательность действий:
- Открыть Диспетчер задач, отключить все процессы, связанные с Дискордом.
- В меню Панели управления найти пункт Программы и компоненты, открыть.
- Найти строку со словом Discord и удалить, после чего повторить пункты 2-4 из предыдущего способа, чтобы найти каталог Discord и удалить его. Затем выйти в AppData, зайти в Roaming и тоже удалить папку под названием Discord.
- Установить клиент Discord заново.
Другие способы
Если ошибка всё же не уходит, то остается проверить систему на предмет вирусов и установить свежие обновления системы Windows.
Если же JavaScript error возникает в других программах или в интернете, что наблюдается намного реже, то все вышеописанные способы будут работать. В случае с приложениями, можно выполнять те же действия, что и с Дискордом, но для нужной программы.
Другие варианты ошибки
Способы исправления всех ошибок идентичны, но иногда исправлять их не обязательно, главное понять, о чем именно предупреждает приложение или сервис:
- “A fatal JavaScript error occurred” (возникла фатальная ошибка) – возникает в Discord, приложение при этом вылетает. Исправляется обновлением или полной переустановкой клиента. Если это не помогает, нужно проверить программу антивирусом, предварительно отключив все процессы Discord, затем запустить программу от имени администратора.
- “JavaScript error: data is not a function” (данные не являются функцией) – возникает в ВК, не открываются сообщения. Обычно помогает очистка кэша браузера.
- “JavaScript error: wall is not defined” (стена не определена) – возникает Вконтакте при обновлении страницы, перестает работать стена. Решается обновлением Java, Adobe Flash Player, чисткой файла hosts, чисткой кэша браузера и перезагрузкой ПК.
- “JavaScript error: poster is not defined” (постер не определен), “JavaScript error: mediaselector is not defined” (медиаселектор не определен) – ошибки Вконтакте, при этом нельзя посмотреть новости и сообщения. Обычно решаются обновлением браузера, Java или Flash Player.
- “JavaScript error: scrollnode is not defined” (узел не определен) – ошибка ВК. Исправить ее нельзя, неполадки на стороне сервера.
- “JavaScript error: profile is not defined” (профиль не определен) – ошибка ВК, некорректно открываются страницы Вконтакте. Для исправления нужно очистить кэш, файл hosts и перезагрузить компьютер.
В целом способы исправления всех ошибок JavaScript идентичны, они актуальны и для таких расшифровок: timespent is not defined, mutations are not initialized, uisearch is not defined, upload is not defined, object is not a function, getaudioplayer updatecurrentplaying и других.
Continuous Test Orchestration And Execution Platform Online
Perform automated and live-interactive testing on 3000+ real desktop and mobile devices online.
Arnab Roy Chowdhury
Posted On: July 27, 2018
20281 Views
5 Min Read
JavaScript is criticized as a language that is quite difficult to debug. It doesn’t matter how perfect the code of a front-end application is, some of its functionality will get impacted especially when we get down to test it’s compatbility across different browsers. The errors occur mostly because many times developers use modern Web API or ECMA 6 scripts in their codes that are not yet browser compatible even in some most popular browser versions. In this article, we will look at the errors commonly faced by developers in their front-end application and how to minimize or get rid of them.
Uncaught TypeError
If you are debugging your JavaScript code in Google Chrome, you may have seen this error for several times. This occurs when you call a method or read a property on an undefined object.

Although this error can occur due to many reasons, a common one is the state of an element not properly initialized when UI components are rendered. Not only in JavaScript, this issue can also occur in an application developed using React JS or Angular jS. Let’s see how to fix it.
Fix – The state should be initialized using a reasonable default value in constructors.
Loading and Runtime Errors
Just like Java and C++ has compile errors, JavaScript has loading errors. Developers will not be able to detect a prominent error until it is loaded in the browser. Once loaded, it can be spotted easily when an error message is displayed showing syntax error. Runtime errors occur when the interpreter comes along some code that it cannot understand. Both loading and syntax errors are simple but can result in unexpected halting of script.
Fix – Once these errors occur, debugger in the browser can be used to find out the error in code. Misspelt syntax, a semicolon that is missed while typing, generally causes this error.

Null Object Error in Safari
This is a major cross browser compatibility issue typically associated with Safari Browsers. Often in Safari, an error occurs, and a message is displayed in the console that null is not an object. This occurs when a method is called on a null object. One can test this easily in the developer console of Safari. If you don’t have a mac system handy, you can try it out at here LambdaTest. We have more than 3000 combinations of browsers and operating systems, including Mac and Safari browsers, where you can test your website for browser compatibility.

Null and undefined are not same in JavaScript. Null means that the object has a blank value. Undefined means a variable that is not assigned. Using a strict equality operator can verify that they are not equal.

This error also occurs when the developer tries to use a DOM element before it is loaded.
Fix – An event listener is the perfect solution for this type of errors. It notifies the developer once the page is ready. The init() method can use the DOM elements once the event listener is fired.
Parse Errors
Often when hard coded values are used in JavaScript, during compilation, the code throws parse error. This occurs mostly when hard line breaks exist in the code. The compiler interprets line breaks as line ending semi-colons.
Fix– Always use parenthesis and semi-colons to make your code easier to read and avoid breaking lines.

(unknown): Script error
When the domain boundary is crossed by an uncaught JavaScript error, it violates the cross-origin policy and results in Script error. Uncaught errors are those which are not caught inside try-catch and bubble up on the window.onerror handler. A common example is, if your JavaScript code is hosted in CDN, any uncaught error gets reported as Script error. This is a security protocol built in browsers to prevent passing of data across domains which is not permitted otherwise.
Fix – Try-catch should always be used to handle errors
TypeError – Property Not Supported by Object
This error usually occurs in Internet Explorer when an undefined method is called. It can be compared to the undefined function error that occur in Chrome. For web applications that use JavaScript namespacing, this error is quite common. IE cannot bind “this” keyword to the current namespace. For example, this.isAwesome() works properly in all browsers but throws an exception in Chrome.

Fix – When using namespacing, this error can be avoided by using the actual namespace as a prefix
TypeError – Cannot Read Length
This error occurs mostly in Chrome due to an undefined variable’s length property. Normally an array has its length defined. But when the variable name of an array remains hidden or if the array is not initialized, this error happens.

Fix – This error can be fixed in 2 ways
- In the statement where the function is declared, parameters should be removed.
- The function should be invoked in the array that is declared.
Most of the errors that occur when the browser compiles the JavaScript are either undefined or null type errors. If the developer uses the strict compiler in a static checking system like Typescript, these errors can be avoided. It will give the warning that a type is not defined but expected. Even if Typescript is not used, guard clauses can be used to check if the objects are undefined before they are used.

Arnab Roy Chowdhury
Arnab Roy Chowdhury is a UI developer by profession and a blogging enthusiast. He has been writing content for about 5 years and has strong expertise in technical blogs, travelogues, and content in the latest programming languages.
![]()


Author’s Profile
Arnab Roy Chowdhury
Arnab Roy Chowdhury is a UI developer by profession and a blogging enthusiast. He has been writing content for about 5 years and has strong expertise in technical blogs, travelogues, and content in the latest programming languages.
Got Questions? Drop them on LambdaTest Community. Visit now
Test your websites, web-apps or mobile apps seamlessly with LambdaTest.
- Selenium, Cypress, Playwright & Puppeteer Testing
- Real Devices Cloud
- Native App Testing
- Appium Testing
- Live Interactive Testing
- Smart Visual UI Testing
Book a Demo
Ошибки¶
Приложения, работающие в Node.js, обычно сталкиваются с четырьмя категориями ошибок:
- Стандартные ошибки JavaScript, такие как {EvalError}, {SyntaxError}, {RangeError}, {ReferenceError}, {TypeError} и {URIError}.
- Системные ошибки, вызванные ограничениями базовой операционной системы, такими как попытка открыть несуществующий файл или попытка отправить данные через закрытый сокет.
- Пользовательские ошибки, вызванные кодом приложения.
AssertionErrors — это особый класс ошибок, который может быть вызван, когда Node.js обнаруживает исключительное логическое нарушение, которое никогда не должно происходить. Обычно они поднимаютсяassertмодуль.
Все ошибки JavaScript и системные ошибки, вызванные Node.js, наследуются от стандартного класса {Error} JavaScript или являются его экземплярами и гарантированно предоставляют по меньшей мере свойства, доступные в этом классе.
Распространение ошибок и перехват¶
Node.js поддерживает несколько механизмов распространения и обработки ошибок, возникающих во время работы приложения. То, как эти ошибки сообщаются и обрабатываются, полностью зависит от типа Error и стиль вызываемого API.
Все ошибки JavaScript обрабатываются как исключения, которые немедленно генерировать и выдавать ошибку с помощью стандартного JavaScript throw механизм. Они обрабатываются с помощью try…catch строить предоставляется языком JavaScript.
// Throws with a ReferenceError because z is not defined.
try {
const m = 1;
const n = m + z;
} catch (err) {
// Handle the error here.
}
Любое использование JavaScript throw механизм вызовет исключение, которое должен обрабатываться с использованием try…catch или процесс Node.js немедленно завершится.
За некоторыми исключениями, Синхронный API (любой метод блокировки, не принимающий callback функция, например fs.readFileSync), буду использовать throw сообщать об ошибках.
Ошибки, возникающие внутри Асинхронные API можно сообщить несколькими способами:
- Большинство асинхронных методов, которые принимают
callbackфункция приметErrorобъект, переданный в качестве первого аргумента этой функции. Если этот первый аргумент неnullи является экземпляромError, то произошла ошибка, которую необходимо обработать.
const fs = require('fs');
fs.readFile('a file that does not exist', (err, data) => {
if (err) {
console.error(
'There was an error reading the file!',
err
);
return;
}
// Otherwise handle the data
});
- Когда асинхронный метод вызывается для объекта, который является
EventEmitter, ошибки могут быть перенаправлены на этот объект'error'событие.
const net = require('net');
const connection = net.connect('localhost');
// Adding an 'error' event handler to a stream:
connection.on('error', (err) => {
// If the connection is reset by the server, or if it can't
// connect at all, or on any sort of error encountered by
// the connection, the error will be sent here.
console.error(err);
});
connection.pipe(process.stdout);
- Некоторые обычно асинхронные методы в API Node.js могут по-прежнему использовать
throwмеханизм для создания исключений, которые должны обрабатываться с помощьюtry…catch. Исчерпывающего списка таких методов нет; обратитесь к документации по каждому методу, чтобы определить соответствующий требуемый механизм обработки ошибок.
Использование 'error' механизм событий наиболее распространен для потоковый а также на основе эмиттера событий API-интерфейсы, которые сами по себе представляют собой серию асинхронных операций с течением времени (в отличие от одной операции, которая может пройти или закончиться неудачей).
Для все EventEmitter объекты, если 'error' обработчик событий не предоставляется, будет выдана ошибка, в результате чего процесс Node.js сообщит о неперехваченном исключении и завершится сбоем, если только одно из следующих событий: domain модуль используется надлежащим образом или обработчик зарегистрирован для 'uncaughtException' событие.
const EventEmitter = require('events');
const ee = new EventEmitter();
setImmediate(() => {
// This will crash the process because no 'error' event
// handler has been added.
ee.emit('error', new Error('This will crash'));
});
Ошибки, сгенерированные таким образом не мочь быть перехваченным с помощью try…catch как они брошены после код вызова уже вышел.
Разработчики должны обращаться к документации по каждому методу, чтобы точно определить, как распространяются ошибки, вызванные этими методами.
Обратные вызовы при первой ошибке¶
Большинство асинхронных методов, предоставляемых основным API Node.js, следуют идиоматическому шаблону, называемому обратный вызов при первой ошибке. В этом шаблоне функция обратного вызова передается методу в качестве аргумента. Когда операция завершается или возникает ошибка, вызывается функция обратного вызова с Error объект (если есть) передается в качестве первого аргумента. Если ошибки не возникло, первый аргумент будет передан как null.
const fs = require('fs');
function errorFirstCallback(err, data) {
if (err) {
console.error('There was an error', err);
return;
}
console.log(data);
}
fs.readFile(
'/some/file/that/does-not-exist',
errorFirstCallback
);
fs.readFile(
'/some/file/that/does-exist',
errorFirstCallback
);
JavaScript try…catch механизм не мочь использоваться для перехвата ошибок, генерируемых асинхронными API. Распространенная ошибка новичков — пытаться использовать throw внутри обратного вызова с ошибкой:
// THIS WILL NOT WORK:
const fs = require('fs');
try {
fs.readFile(
'/some/file/that/does-not-exist',
(err, data) => {
// Mistaken assumption: throwing here...
if (err) {
throw err;
}
}
);
} catch (err) {
// This will not catch the throw!
console.error(err);
}
Это не сработает, потому что функция обратного вызова передана в fs.readFile() вызывается асинхронно. К моменту вызова обратного вызова окружающий код, включая try…catch блок, уже вышли. Выдача ошибки внутри обратного вызова может привести к сбою процесса Node.js в большинстве случаев. Если домены включены, или обработчик был зарегистрирован с process.on('uncaughtException'), такие ошибки можно перехватить.
Класс: Error¶
Общий объект JavaScript {Error}, не указывающий на конкретную причину возникновения ошибки. Error объекты фиксируют «трассировку стека», детализирующую точку в коде, в которой Error был создан, и может содержать текстовое описание ошибки.
Все ошибки, генерируемые Node.js, включая все системные ошибки и ошибки JavaScript, будут либо экземплярами, либо унаследованы от Error класс.
new Error(message)¶
message{нить}
Создает новый Error объект и устанавливает error.message в предоставленное текстовое сообщение. Если объект передается как message, текстовое сообщение создается при вызове message.toString(). В error.stack свойство будет представлять точку в коде, в которой new Error() назывался. Трассировки стека зависят от API трассировки стека V8. Трассировки стека распространяются только на (а) начало синхронное выполнение кода, или (b) количество кадров, заданное свойством Error.stackTraceLimit, в зависимости от того, что меньше.
Error.captureStackTrace(targetObject[, constructorOpt])¶
targetObject{Объект}constructorOpt{Функция}
Создает .stack собственность на targetObject, который при доступе возвращает строку, представляющую место в коде, в котором Error.captureStackTrace() назывался.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack; // Similar to `new Error().stack`
Первая строка трассировки будет иметь префикс ${myObject.name}: ${myObject.message}.
Необязательный constructorOpt Аргумент принимает функцию. Если указано, все кадры выше constructorOpt, включая constructorOpt, будет исключен из сгенерированной трассировки стека.
В constructorOpt Аргумент полезен для сокрытия деталей реализации генерации ошибок от пользователя. Например:
function MyError() {
Error.captureStackTrace(this, MyError);
}
// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame, and retain all frames below it.
new MyError().stack;
Error.stackTraceLimit¶
- {количество}
В Error.stackTraceLimit указывает количество кадров стека, собранных трассировкой стека (независимо от того, сгенерированы ли они new Error().stack или Error.captureStackTrace(obj)).
Значение по умолчанию — 10 но может быть установлен на любой допустимый номер JavaScript. Изменения повлияют на любую записанную трассировку стека. после значение было изменено.
Если установлено нечисловое значение или задано отрицательное число, трассировки стека не будут захватывать какие-либо кадры.
error.code¶
- {нить}
В error.code Свойство — это строковая метка, определяющая тип ошибки. error.code это наиболее стабильный способ выявления ошибки. Он будет меняться только между основными версиями Node.js. Наоборот, error.message строки могут меняться между любыми версиями Node.js. Видеть Коды ошибок Node.js для получения подробной информации о конкретных кодах.
error.message¶
- {нить}
В error.message свойство — это строковое описание ошибки, установленное при вызове new Error(message). В message переданный конструктору, также появится в первой строке трассировки стека Error, однако изменение этого свойства после Error объект создан может нет изменить первую строку трассировки стека (например, когда error.stack читается до изменения этого свойства).
const err = new Error('The message');
console.error(err.message);
// Prints: The message
error.stack¶
- {нить}
В error.stack свойство — это строка, описывающая точку в коде, в которой Error был создан.
Error: Things keep happening!
at /home/gbusey/file.js:525:2
at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
at increaseSynergy (/home/gbusey/actors.js:701:6)
Первая строка отформатирована как <error class name>: <error message>, за которым следует серия кадров стека (каждая строка начинается с «at»). Каждый фрейм описывает сайт вызова в коде, который приводит к сгенерированной ошибке. V8 пытается отобразить имя для каждой функции (по имени переменной, имени функции или имени метода объекта), но иногда не может найти подходящее имя. Если V8 не может определить имя функции, для этого фрейма будет отображаться только информация о местоположении. В противном случае определенное имя функции будет отображаться с информацией о местоположении, добавленной в круглые скобки.
Фреймы создаются только для функций JavaScript. Если, например, выполнение синхронно проходит через дополнительную функцию C ++, называемую cheetahify который сам вызывает функцию JavaScript, фрейм, представляющий cheetahify вызов не будет присутствовать в трассировке стека:
const cheetahify = require('./native-binding.node');
function makeFaster() {
// `cheetahify()` *synchronously* calls speedy.
cheetahify(function speedy() {
throw new Error('oh no!');
});
}
makeFaster();
// will throw:
// /home/gbusey/file.js:6
// throw new Error('oh no!');
// ^
// Error: oh no!
// at speedy (/home/gbusey/file.js:6:11)
// at makeFaster (/home/gbusey/file.js:5:3)
// at Object.<anonymous> (/home/gbusey/file.js:10:1)
// at Module._compile (module.js:456:26)
// at Object.Module._extensions..js (module.js:474:10)
// at Module.load (module.js:356:32)
// at Function.Module._load (module.js:312:12)
// at Function.Module.runMain (module.js:497:10)
// at startup (node.js:119:16)
// at node.js:906:3
Информация о местоположении будет одной из следующих:
native, если кадр представляет внутренний вызов V8 (как в[].forEach).plain-filename.js:line:column, если фрейм представляет собой внутренний вызов Node.js./absolute/path/to/file.js:line:column, если кадр представляет собой вызов в пользовательской программе или ее зависимостях.
Строка, представляющая трассировку стека, генерируется лениво, когда error.stack собственность доступ.
Количество кадров, захваченных трассировкой стека, ограничено меньшим из Error.stackTraceLimit или количество доступных кадров в текущем тике цикла событий.
Класс: AssertionError¶
- Расширяется: {errors.Error}
Указывает на неудачу утверждения. Подробнее см. Class: assert.AssertionError.
Класс: RangeError¶
- Расширяется: {errors.Error}
Указывает, что предоставленный аргумент находится за пределами набора или диапазона допустимых значений для функции; является ли это числовым диапазоном или вне набора опций для данного параметра функции.
require('net').connect(-1);
// Throws "RangeError: "port" option should be >= 0 and < 65536: -1"
Node.js сгенерирует и выбросит RangeError экземпляры немедленно как форма подтверждения аргумента.
Класс: ReferenceError¶
- Расширяется: {errors.Error}
Указывает, что предпринимается попытка получить доступ к переменной, которая не определена. Такие ошибки обычно указывают на опечатки в коде или на некорректную программу.
Хотя клиентский код может генерировать и распространять эти ошибки, на практике это будет делать только V8.
doesNotExist;
// Throws ReferenceError, doesNotExist is not a variable in this program.
Если приложение динамически не генерирует и не запускает код, ReferenceError экземпляры указывают на ошибку в коде или его зависимостях.
Класс: SyntaxError¶
- Расширяется: {errors.Error}
Указывает, что программа не является допустимым JavaScript. Эти ошибки могут возникать и распространяться только в результате оценки кода. Оценка кода может произойти в результате eval, Function, require, или vm. Эти ошибки почти всегда указывают на неработающую программу.
try {
require('vm').runInThisContext('binary ! isNotOk');
} catch (err) {
// 'err' will be a SyntaxError.
}
SyntaxError экземпляры невозможно восстановить в контексте, который их создал — они могут быть перехвачены только в других контекстах.
Класс: SystemError¶
- Расширяется: {errors.Error}
Node.js генерирует системные ошибки, когда в среде выполнения возникают исключения. Обычно это происходит, когда приложение нарушает ограничение операционной системы. Например, системная ошибка произойдет, если приложение попытается прочитать несуществующий файл.
address{строка} Если присутствует, адрес, к которому не удалось подключиться к сети.code{строка} Код ошибки строкиdest{строка} Если присутствует, путь к файлу при сообщении об ошибке файловой системыerrno{number} Номер ошибки, предоставленный системойinfo{Object} Если присутствует, дополнительные сведения о состоянии ошибкиmessage{string} Предоставляемое системой описание ошибки в удобной для чтения форме.path{строка} Если присутствует, путь к файлу при сообщении об ошибке файловой системыport{number} Если присутствует, порт сетевого подключения, который недоступенsyscall{строка} Имя системного вызова, вызвавшего ошибку
error.address¶
- {нить}
Если представить, error.address — это строка, описывающая адрес, к которому не удалось установить сетевое соединение.
error.code¶
- {нить}
В error.code свойство — это строка, представляющая код ошибки.
error.dest¶
- {нить}
Если представить, error.dest — это путь к файлу при сообщении об ошибке файловой системы.
error.errno¶
- {количество}
В error.errno свойство — отрицательное число, которое соответствует коду ошибки, определенному в libuv Error handling.
В Windows номер ошибки, предоставленный системой, будет нормализован libuv.
Чтобы получить строковое представление кода ошибки, используйте util.getSystemErrorName(error.errno).
error.info¶
- {Объект}
Если представить, error.info — объект с подробной информацией о состоянии ошибки.
error.message¶
- {нить}
error.message представляет собой удобочитаемое описание ошибки, предоставляемое системой.
error.path¶
- {нить}
Если представить, error.path — строка, содержащая соответствующий недопустимый путь.
error.port¶
- {количество}
Если представить, error.port порт сетевого подключения недоступен.
error.syscall¶
- {нить}
В error.syscall свойство — это строка, описывающая системный вызов это не удалось.
Общие системные ошибки¶
Это список системных ошибок, которые часто встречаются при написании программы на Node.js. Полный список см. В errno(3) справочная страница.
-
EACCES(В разрешении отказано): была сделана попытка получить доступ к файлу способом, запрещенным его разрешениями на доступ к файлу. -
EADDRINUSE(Адрес уже используется): попытка привязать сервер (net,http, илиhttps) на локальный адрес не удалось из-за того, что другой сервер в локальной системе уже занимает этот адрес. -
ECONNREFUSED(В соединении отказано): соединение не может быть установлено, потому что целевая машина активно отказалась от него. Обычно это происходит из-за попытки подключиться к неактивной службе на чужом хосте. -
ECONNRESET(Сброс соединения одноранговым узлом): соединение было принудительно закрыто одноранговым узлом. Обычно это происходит из-за потери соединения с удаленным сокетом из-за тайм-аута или перезагрузки. Обычно встречается черезhttpа такжеnetмодули. -
EEXIST(Файл существует): существующий файл был целью операции, которая требовала, чтобы цель не существовала. -
EISDIR(Является каталогом): операция ожидала файл, но указанный путь был каталогом. -
EMFILE(Слишком много открытых файлов в системе): максимальное количество файловые дескрипторы допустимый в системе, и запросы для другого дескриптора не могут быть выполнены, пока хотя бы один из них не будет закрыт. Это происходит при одновременном открытии множества файлов одновременно, особенно в системах (в частности, macOS), где существует низкий предел дескрипторов файлов для процессов. Чтобы исправить низкий предел, запуститеulimit -n 2048в той же оболочке, которая будет запускать процесс Node.js. -
ENOENT(Нет такого файла или каталога): обычно создаетсяfsоперации, чтобы указать, что компонент указанного пути не существует. По указанному пути не удалось найти ни один объект (файл или каталог). -
ENOTDIR(Не каталог): компонент с указанным путем существует, но не является каталогом, как ожидалось. Обычно выращиваетсяfs.readdir. -
ENOTEMPTY(Каталог не пустой): каталог с записями был целью операции, для которой требуется пустой каталог, обычноfs.unlink. -
ENOTFOUND(Ошибка поиска DNS): указывает на сбой DNS либоEAI_NODATAилиEAI_NONAME. Это не стандартная ошибка POSIX. -
EPERM(Операция запрещена): была сделана попытка выполнить операцию, требующую повышенных привилегий. -
EPIPE(Сломанный канал): запись в канал, сокет или FIFO, для которого нет процесса для чтения данных. Часто встречается наnetа такжеhttpУровни, указывающие на то, что удаленная сторона записываемого потока была закрыта. -
ETIMEDOUT(Превышено время ожидания операции): запрос на подключение или отправку завершился неудачно, поскольку подключенная сторона не ответила должным образом по прошествии определенного периода времени. Обычно встречаетсяhttpилиnet. Часто признак того, чтоsocket.end()не был должным образом назван.
Класс: TypeError¶
- Расширяет {errors.Error}
Указывает, что указанный аргумент не является допустимым типом. Например, передача функции параметру, который ожидает строку, будет TypeError.
require('url').parse(() => {});
// Throws TypeError, since it expected a string.
Node.js сгенерирует и выбросит TypeError экземпляры немедленно как форма подтверждения аргумента.
Исключения против ошибок¶
Исключение JavaScript — это значение, которое выбрасывается в результате недопустимой операции или как цель throw утверждение. Хотя не требуется, чтобы эти значения были экземплярами Error или классы, которые наследуются от Error, все исключения, создаваемые Node.js или средой выполнения JavaScript буду быть экземплярами Error.
Некоторые исключения безвозвратно на уровне JavaScript. Такие исключения будут всегда вызвать сбой процесса Node.js. Примеры включают assert() чеки или abort() вызывает в слое C ++.
Ошибки OpenSSL¶
Ошибки, возникающие в crypto или tls классные Error, и в дополнение к стандартному .code а также .message properties, могут иметь некоторые дополнительные свойства, специфичные для OpenSSL.
error.opensslErrorStack¶
Массив ошибок, который может дать контекст, откуда в библиотеке OpenSSL возникла ошибка.
error.function¶
Функция OpenSSL, в которой возникла ошибка.
error.library¶
Библиотека OpenSSL, в которой возникла ошибка.
error.reason¶
Строка в удобном для чтения виде, описывающая причину ошибки.
ABORT_ERR¶
Используется, когда операция была прервана (обычно с использованием AbortController).
API нет с использованием AbortSignals обычно не вызывают ошибки с этим кодом.
Этот код не использует обычный ERR_* соглашение об ошибках Node.js используется для обеспечения совместимости с веб-платформой. AbortError.
ERR_AMBIGUOUS_ARGUMENT¶
Аргумент функции используется таким образом, чтобы предположить, что сигнатура функции может быть неправильно понята. Это брошено assert модуль, когда message параметр в assert.throws(block, message) совпадает с сообщением об ошибке, выданным block потому что это использование предполагает, что пользователь верит message ожидаемое сообщение, а не сообщение AssertionError будет отображаться, если block не бросает.
ERR_ARG_NOT_ITERABLE¶
Итерируемый аргумент (т.е. значение, которое работает с for...of loops) требуется, но не предоставляется API Node.js.
ERR_ASSERTION¶
Особый тип ошибки, которая может быть вызвана всякий раз, когда Node.js обнаруживает исключительное логическое нарушение, которое никогда не должно происходить. Обычно они поднимаются assert модуль.
ERR_ASYNC_CALLBACK¶
Была сделана попытка зарегистрировать что-то, что не является функцией, как AsyncHooks Перезвоните.
ERR_ASYNC_TYPE¶
Недопустимый тип асинхронного ресурса. Пользователи также могут определять свои собственные типы при использовании общедоступного API для встраивания.
ERR_BROTLI_COMPRESSION_FAILED¶
Данные, переданные в поток Brotli, не были успешно сжаты.
ERR_BROTLI_INVALID_PARAM¶
Во время построения потока Brotli был передан недопустимый ключ параметра.
ERR_BUFFER_CONTEXT_NOT_AVAILABLE¶
Была сделана попытка создать Node.js Buffer из кода надстройки или встраивания, находясь в контексте механизма JS, который не связан с экземпляром Node.js. Данные, переданные в Buffer будет выпущен к тому времени, когда метод вернется.
При возникновении этой ошибки возможная альтернатива созданию Buffer пример — создать нормальный Uint8Array, который отличается только прототипом результирующего объекта. Uint8Arrays общеприняты во всех основных API Node.js, где Buffers есть; они доступны во всех контекстах.
ERR_BUFFER_OUT_OF_BOUNDS¶
Операция за пределами Buffer была предпринята попытка.
ERR_BUFFER_TOO_LARGE¶
Была сделана попытка создать Buffer больше максимально допустимого размера.
ERR_CANNOT_WATCH_SIGINT¶
Node.js не смог отследить SIGINT сигнал.
ERR_CHILD_CLOSED_BEFORE_REPLY¶
Дочерний процесс был закрыт до того, как родительский процесс получил ответ.
ERR_CHILD_PROCESS_IPC_REQUIRED¶
Используется, когда дочерний процесс разветвляется без указания канала IPC.
ERR_CHILD_PROCESS_STDIO_MAXBUFFER¶
Используется, когда основной процесс пытается прочитать данные из STDERR / STDOUT дочернего процесса, и длина данных больше, чем maxBuffer вариант.
ERR_CLOSED_MESSAGE_PORT¶
Была попытка использовать MessagePort экземпляр в закрытом состоянии, обычно после .close() был вызван.
ERR_CONSOLE_WRITABLE_STREAM¶
Console был создан без stdout поток, или Console имеет незаписываемый stdout или stderr транслировать.
ERR_CONSTRUCT_CALL_INVALID¶
Был вызван конструктор класса, который нельзя вызвать.
ERR_CONSTRUCT_CALL_REQUIRED¶
Конструктор класса был вызван без new.
ERR_CONTEXT_NOT_INITIALIZED¶
Контекст vm, переданный в API, еще не инициализирован. Это может произойти при возникновении (и обнаружении) ошибки во время создания контекста, например, при сбое выделения или при достижении максимального размера стека вызовов при создании контекста.
ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED¶
Был запрошен механизм сертификатов клиента, который не поддерживается используемой версией OpenSSL.
ERR_CRYPTO_ECDH_INVALID_FORMAT¶
Недопустимое значение для format аргумент был передан crypto.ECDH() класс getPublicKey() метод.
ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY¶
Недопустимое значение для key аргумент был передан crypto.ECDH() класс computeSecret() метод. Это означает, что открытый ключ лежит за пределами эллиптической кривой.
ERR_CRYPTO_ENGINE_UNKNOWN¶
Неверный идентификатор криптографической машины был передан в require('crypto').setEngine().
ERR_CRYPTO_FIPS_FORCED¶
В --force-fips был использован аргумент командной строки, но была попытка включить или отключить режим FIPS в crypto модуль.
ERR_CRYPTO_FIPS_UNAVAILABLE¶
Была сделана попытка включить или отключить режим FIPS, но режим FIPS был недоступен.
ERR_CRYPTO_HASH_FINALIZED¶
hash.digest() вызвали несколько раз. В hash.digest() метод должен вызываться не более одного раза для каждого экземпляра Hash объект.
ERR_CRYPTO_HASH_UPDATE_FAILED¶
hash.update() не удалось по какой-либо причине. Это должно происходить редко, если вообще когда-либо случаться.
ERR_CRYPTO_INCOMPATIBLE_KEY¶
Указанные криптографические ключи несовместимы с предпринятой операцией.
ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS¶
Выбранная кодировка открытого или закрытого ключа несовместима с другими параметрами.
ERR_CRYPTO_INITIALIZATION_FAILED¶
Не удалось инициализировать криптоподсистему.
ERR_CRYPTO_INVALID_AUTH_TAG¶
Предоставлен недопустимый тег аутентификации.
ERR_CRYPTO_INVALID_COUNTER¶
Для шифра режима противодействия предоставлен неверный счетчик.
ERR_CRYPTO_INVALID_CURVE¶
Была предоставлена неверная эллиптическая кривая.
ERR_CRYPTO_INVALID_DIGEST¶
Недействительный алгоритм криптодайджеста было указано.
ERR_CRYPTO_INVALID_IV¶
Предоставлен недопустимый вектор инициализации.
ERR_CRYPTO_INVALID_JWK¶
Был предоставлен недопустимый веб-ключ JSON.
ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE¶
Данный тип объекта криптографического ключа недопустим для выполняемой операции.
ERR_CRYPTO_INVALID_KEYLEN¶
Была предоставлена неверная длина ключа.
ERR_CRYPTO_INVALID_KEYPAIR¶
Была предоставлена неверная пара ключей.
ERR_CRYPTO_INVALID_KEYTYPE¶
Предоставлен недопустимый тип ключа.
ERR_CRYPTO_INVALID_MESSAGELEN¶
Была предоставлена неверная длина сообщения.
ERR_CRYPTO_INVALID_SCRYPT_PARAMS¶
Были предоставлены неверные параметры алгоритма шифрования.
ERR_CRYPTO_INVALID_STATE¶
Крипто-метод был использован для объекта, находившегося в недопустимом состоянии. Например, позвонив cipher.getAuthTag() перед звонком cipher.final().
ERR_CRYPTO_INVALID_TAG_LENGTH¶
Предоставлена неверная длина тега аутентификации.
ERR_CRYPTO_JOB_INIT_FAILED¶
Не удалось инициализировать асинхронную криптооперацию.
ERR_CRYPTO_JWK_UNSUPPORTED_CURVE¶
Эллиптическая кривая Ключа не зарегистрирована для использования в Реестр эллиптических кривых веб-ключей JSON.
ERR_CRYPTO_JWK_UNSUPPORTED_KEY_TYPE¶
Тип асимметричного ключа ключа не зарегистрирован для использования в Реестр типов веб-ключей JSON.
ERR_CRYPTO_OPERATION_FAILED¶
Криптооперация завершилась неудачно по неустановленной причине.
ERR_CRYPTO_PBKDF2_ERROR¶
Алгоритм PBKDF2 завершился неудачно по неустановленным причинам. OpenSSL не предоставляет более подробной информации, и, следовательно, Node.js.
ERR_CRYPTO_SCRYPT_INVALID_PARAMETER¶
Один или больше crypto.scrypt() или crypto.scryptSync() параметры находятся за пределами допустимого диапазона.
ERR_CRYPTO_SCRYPT_NOT_SUPPORTED¶
Node.js был скомпилирован без scrypt служба поддержки. Невозможно с официальными двоичными файлами выпуска, но может произойти с пользовательскими сборками, включая сборки дистрибутива.
ERR_CRYPTO_SIGN_KEY_REQUIRED¶
Подпись key не был предоставлен sign.sign() метод.
ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH¶
crypto.timingSafeEqual() был вызван с Buffer, TypedArray, или DataView аргументы разной длины.
ERR_CRYPTO_UNKNOWN_CIPHER¶
Указан неизвестный шифр.
ERR_CRYPTO_UNKNOWN_DH_GROUP¶
Было дано неизвестное название группы Диффи-Хеллмана. Видеть crypto.getDiffieHellman() для списка допустимых имен групп.
ERR_CRYPTO_UNSUPPORTED_OPERATION¶
Была сделана попытка вызвать неподдерживаемую криптографическую операцию.
ERR_DEBUGGER_ERROR¶
Произошла ошибка с отладчик.
ERR_DEBUGGER_STARTUP_ERROR¶
В отладчик истекло время ожидания освобождения необходимого хоста / порта.
ERR_DLOPEN_DISABLED¶
Загрузка собственных надстроек отключена с помощью --no-addons.
ERR_DLOPEN_FAILED¶
Звонок в process.dlopen() не смогли.
ERR_DIR_CLOSED¶
В fs.Dir ранее был закрыт.
ERR_DIR_CONCURRENT_OPERATION¶
Была предпринята попытка синхронного чтения или закрытия fs.Dir который имеет текущие асинхронные операции.
ERR_DNS_SET_SERVERS_FAILED¶
c-ares не удалось установить DNS-сервер.
ERR_DOMAIN_CALLBACK_NOT_AVAILABLE¶
В domain модуль нельзя было использовать, так как он не мог установить требуемые перехватчики обработки ошибок, потому что process.setUncaughtExceptionCaptureCallback() был вызван в более ранний момент времени.
ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE¶
process.setUncaughtExceptionCaptureCallback() нельзя было назвать, потому что domain модуль был загружен раньше.
Трассировка стека расширяется, чтобы включить момент времени, в который domain модуль был загружен.
ERR_ENCODING_INVALID_ENCODED_DATA¶
Данные предоставлены TextDecoder() API был недопустимым в соответствии с предоставленной кодировкой.
ERR_ENCODING_NOT_SUPPORTED¶
Кодировка предоставлена TextDecoder() API не был одним из WHATWG Поддерживаемые кодировки.
ERR_EVAL_ESM_CANNOT_PRINT¶
--print не может использоваться с входом ESM.
ERR_EVENT_RECURSION¶
Вызывается, когда делается попытка рекурсивно отправить событие на EventTarget.
ERR_EXECUTION_ENVIRONMENT_NOT_AVAILABLE¶
Контекст выполнения JS не связан со средой Node.js. Это может произойти, если Node.js используется в качестве встроенной библиотеки и некоторые хуки для движка JS не настроены должным образом.
ERR_FALSY_VALUE_REJECTION¶
А Promise это было выполнено обратным вызовом через util.callbackify() был отклонен с ложным значением.
ERR_FEATURE_UNAVAILABLE_ON_PLATFORM¶
Используется, когда используется функция, недоступная для текущей платформы, на которой работает Node.js.
ERR_FS_CP_DIR_TO_NON_DIR¶
Была сделана попытка скопировать каталог в не каталог (файл, символическую ссылку и т. Д.) С помощью fs.cp().
ERR_FS_CP_EEXIST¶
Была сделана попытка скопировать файл, который уже существовал с fs.cp(), с force а также errorOnExist установлен в true.
ERR_FS_CP_EINVAL¶
Когда используешь fs.cp(), src или dest указал на недопустимый путь.
ERR_FS_CP_FIFO_PIPE¶
Была сделана попытка скопировать именованный канал с fs.cp().
ERR_FS_CP_NON_DIR_TO_DIR¶
Была сделана попытка скопировать не каталог (файл, символическую ссылку и т. Д.) В каталог с помощью fs.cp().
ERR_FS_CP_SOCKET¶
Была сделана попытка скопировать в сокет с fs.cp().
ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY¶
Когда используешь fs.cp(), символическая ссылка в dest указал на подкаталог src.
ERR_FS_CP_UNKNOWN¶
Была сделана попытка скопировать файл неизвестного типа с fs.cp().
ERR_FS_EISDIR¶
Путь — это каталог.
ERR_FS_FILE_TOO_LARGE¶
Была сделана попытка прочитать файл, размер которого превышает максимально допустимый размер для Buffer.
ERR_FS_INVALID_SYMLINK_TYPE¶
Недопустимый тип символической ссылки был передан в fs.symlink() или fs.symlinkSync() методы.
Была сделана попытка добавить дополнительные заголовки после того, как они уже были отправлены.
Указано недопустимое значение заголовка HTTP.
ERR_HTTP_INVALID_STATUS_CODE¶
Код состояния находился за пределами обычного диапазона кодов состояния (100–999).
ERR_HTTP_REQUEST_TIMEOUT¶
Клиент не отправил весь запрос в отведенное время.
ERR_HTTP_SOCKET_ENCODING¶
Изменение кодировки сокета запрещено RFC 7230, раздел 3.
ERR_HTTP_TRAILER_INVALID¶
В Trailer заголовок был установлен, хотя кодировка передачи не поддерживает это.
ERR_HTTP2_ALTSVC_INVALID_ORIGIN¶
Для фреймов HTTP / 2 ALTSVC требуется действительное происхождение.
ERR_HTTP2_ALTSVC_LENGTH¶
Кадры HTTP / 2 ALTSVC ограничены максимум 16 382 байтами полезной нагрузки.
Для запросов HTTP / 2 с использованием CONNECT метод, :authority псевдозаголовок обязателен.
ERR_HTTP2_CONNECT_PATH¶
Для запросов HTTP / 2 с использованием CONNECT метод, :path псевдозаголовок запрещен.
ERR_HTTP2_CONNECT_SCHEME¶
Для запросов HTTP / 2 с использованием CONNECT метод, :scheme псевдозаголовок запрещен.
ERR_HTTP2_ERROR¶
Произошла неспецифическая ошибка HTTP / 2.
ERR_HTTP2_GOAWAY_SESSION¶
Новые потоки HTTP / 2 нельзя открывать после Http2Session получил GOAWAY кадр от подключенного однорангового узла.
Было предоставлено несколько значений для поля заголовка HTTP / 2, которое должно было иметь только одно значение.
Дополнительные заголовки были указаны после того, как был инициирован ответ HTTP / 2.
Была сделана попытка отправить несколько заголовков ответа.
ERR_HTTP2_INFO_STATUS_NOT_ALLOWED¶
Информационные коды состояния HTTP (1xx) не может быть установлен в качестве кода состояния ответа в ответах HTTP / 2.
Заголовки соединения HTTP / 1 запрещено использовать в запросах и ответах HTTP / 2.
Указано недопустимое значение заголовка HTTP / 2.
ERR_HTTP2_INVALID_INFO_STATUS¶
Указан недопустимый информационный код состояния HTTP. Информационные коды состояния должны быть целыми числами между 100 а также 199 (включительно).
ERR_HTTP2_INVALID_ORIGIN¶
HTTP / 2 ORIGIN кадры требуют действительного происхождения.
ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH¶
Вход Buffer а также Uint8Array экземпляры переданы в http2.getUnpackedSettings() API должен иметь длину, кратную шести.
Только допустимые псевдозаголовки HTTP / 2 (:status, :path, :authority, :scheme, а также :method) может быть использовано.
ERR_HTTP2_INVALID_SESSION¶
Действие было выполнено с Http2Session объект, который уже был уничтожен.
ERR_HTTP2_INVALID_SETTING_VALUE¶
Для параметра HTTP / 2 указано недопустимое значение.
ERR_HTTP2_INVALID_STREAM¶
Операция была выполнена над потоком, который уже был уничтожен.
ERR_HTTP2_MAX_PENDING_SETTINGS_ACK¶
Всякий раз, когда HTTP / 2 SETTINGS фрейм отправляется подключенному одноранговому узлу, одноранговый узел должен отправить подтверждение, что он получил и применил новый SETTINGS. По умолчанию максимальное количество неподтвержденных SETTINGS кадры могут быть отправлены в любой момент времени. Этот код ошибки используется при достижении этого предела.
ERR_HTTP2_NESTED_PUSH¶
Была сделана попытка инициировать новый push-поток из push-потока. Вложенные push-потоки не разрешены.
ERR_HTTP2_NO_MEM¶
Недостаточно памяти при использовании http2session.setLocalWindowSize(windowSize) API.
ERR_HTTP2_NO_SOCKET_MANIPULATION¶
Была предпринята попытка напрямую манипулировать (чтение, запись, пауза, возобновление и т. Д.) Сокетом, подключенным к Http2Session.
ERR_HTTP2_ORIGIN_LENGTH¶
HTTP / 2 ORIGIN кадры ограничены длиной 16382 байта.
ERR_HTTP2_OUT_OF_STREAMS¶
Количество потоков, созданных в одном сеансе HTTP / 2, достигло максимального предела.
ERR_HTTP2_PAYLOAD_FORBIDDEN¶
Полезная нагрузка сообщения была указана для кода ответа HTTP, для которого полезная нагрузка запрещена.
ERR_HTTP2_PING_CANCEL¶
Пинг HTTP / 2 был отменен.
ERR_HTTP2_PING_LENGTH¶
Полезные данные ping HTTP / 2 должны иметь длину ровно 8 байтов.
Псевдозаголовок HTTP / 2 использован ненадлежащим образом. Псевдо-заголовки — это имена ключей заголовков, которые начинаются с : приставка.
ERR_HTTP2_PUSH_DISABLED¶
Была сделана попытка создать push-поток, который был отключен клиентом.
ERR_HTTP2_SEND_FILE¶
Была сделана попытка использовать Http2Stream.prototype.responseWithFile() API для отправки каталога.
ERR_HTTP2_SEND_FILE_NOSEEK¶
Была сделана попытка использовать Http2Stream.prototype.responseWithFile() API для отправки чего-то другого, кроме обычного файла, но offset или length были предоставлены варианты.
ERR_HTTP2_SESSION_ERROR¶
В Http2Session закрывается с ненулевым кодом ошибки.
ERR_HTTP2_SETTINGS_CANCEL¶
В Http2Session настройки отменены.
ERR_HTTP2_SOCKET_BOUND¶
Была сделана попытка подключить Http2Session возражать против net.Socket или tls.TLSSocket который уже был привязан к другому Http2Session объект.
ERR_HTTP2_SOCKET_UNBOUND¶
Была сделана попытка использовать socket собственность Http2Session это уже было закрыто.
ERR_HTTP2_STATUS_101¶
Использование 101 Информационный код статуса запрещен в HTTP / 2.
ERR_HTTP2_STATUS_INVALID¶
Указан недопустимый код состояния HTTP. Коды состояния должны быть целыми числами между 100 а также 599 (включительно).
ERR_HTTP2_STREAM_CANCEL¶
An Http2Stream был уничтожен до того, как какие-либо данные были переданы подключенному узлу.
ERR_HTTP2_STREAM_ERROR¶
Ненулевой код ошибки был указан в RST_STREAM Рамка.
ERR_HTTP2_STREAM_SELF_DEPENDENCY¶
При установке приоритета для потока HTTP / 2 этот поток может быть помечен как зависимость для родительского потока. Этот код ошибки используется, когда делается попытка пометить поток и зависит от него самого.
ERR_HTTP2_TOO_MANY_INVALID_FRAMES¶
Предел приемлемых недопустимых кадров протокола HTTP / 2, отправленных партнером, как указано в maxSessionInvalidFrames вариант, был превышен.
ERR_HTTP2_TRAILERS_ALREADY_SENT¶
Конечные заголовки уже отправлены на Http2Stream.
ERR_HTTP2_TRAILERS_NOT_READY¶
В http2stream.sendTrailers() метод не может быть вызван до тех пор, пока 'wantTrailers' событие испускается на Http2Stream объект. В 'wantTrailers' событие будет сгенерировано только в том случае, если waitForTrailers опция установлена для Http2Stream.
ERR_HTTP2_UNSUPPORTED_PROTOCOL¶
http2.connect() был передан URL-адрес, использующий любой протокол, кроме http: или https:.
ERR_ILLEGAL_CONSTRUCTOR¶
Была предпринята попытка построить объект с использованием закрытого конструктора.
ERR_INCOMPATIBLE_OPTION_PAIR¶
Пара опций несовместима друг с другом и не может использоваться одновременно.
ERR_INPUT_TYPE_NOT_ALLOWED¶
Стабильность: 1 — экспериментальная
В --input-type Флаг использовался для попытки выполнить файл. Этот флаг можно использовать только при вводе через --eval, --print или STDIN.
ERR_INSPECTOR_ALREADY_ACTIVATED¶
При использовании inspector module была предпринята попытка активировать инспектор, когда он уже начал прослушивать порт. Использовать inspector.close() прежде чем активировать его на другом адресе.
ERR_INSPECTOR_ALREADY_CONNECTED¶
При использовании inspector модуль, была предпринята попытка подключения, когда инспектор уже был подключен.
ERR_INSPECTOR_CLOSED¶
При использовании inspector модуля, была предпринята попытка использовать инспектор после того, как сессия уже закрылась.
ERR_INSPECTOR_COMMAND¶
Произошла ошибка при подаче команды через inspector модуль.
ERR_INSPECTOR_NOT_ACTIVE¶
В inspector не активен, когда inspector.waitForDebugger() называется.
ERR_INSPECTOR_NOT_AVAILABLE¶
В inspector модуль недоступен для использования.
ERR_INSPECTOR_NOT_CONNECTED¶
При использовании inspector модуль, была предпринята попытка использовать инспектор до его подключения.
ERR_INSPECTOR_NOT_WORKER¶
В основном потоке был вызван API, который можно использовать только из рабочего потока.
ERR_INTERNAL_ASSERTION¶
Ошибка в Node.js или некорректное использование внутренних компонентов Node.js. Чтобы исправить ошибку, откройте проблему на https://github.com/nodejs/node/issues.
ERR_INVALID_ADDRESS_FAMILY¶
Указанное семейство адресов не распознается API Node.js.
ERR_INVALID_ARG_TYPE¶
В API Node.js был передан аргумент неправильного типа.
ERR_INVALID_ARG_VALUE¶
Для данного аргумента было передано недопустимое или неподдерживаемое значение.
ERR_INVALID_ASYNC_ID¶
Недействительный asyncId или triggerAsyncId был передан с использованием AsyncHooks. Идентификатор меньше -1 никогда не должен происходить.
ERR_INVALID_BUFFER_SIZE¶
Обмен был произведен на Buffer но его размер был несовместим с операцией.
ERR_INVALID_CALLBACK¶
Требовалась функция обратного вызова, но она не была предоставлена API Node.js.
ERR_INVALID_CHAR¶
В заголовках обнаружены недопустимые символы.
ERR_INVALID_CURSOR_POS¶
Курсор в данном потоке нельзя переместить в указанную строку без указанного столбца.
ERR_INVALID_FD¶
Дескриптор файла (‘fd’) недействителен (например, имеет отрицательное значение).
ERR_INVALID_FD_TYPE¶
Недопустимый тип дескриптора файла (‘fd’).
ERR_INVALID_FILE_URL_HOST¶
API-интерфейс Node.js, который потребляет file: URL-адреса (например, определенные функции в fs module) обнаружил URL-адрес файла с несовместимым хостом. Эта ситуация может возникнуть только в Unix-подобных системах, где только localhost или поддерживается пустой хост.
ERR_INVALID_FILE_URL_PATH¶
API-интерфейс Node.js, который потребляет file: URL-адреса (например, определенные функции в fs module) обнаружил URL-адрес файла с несовместимым путем. Точная семантика для определения возможности использования пути зависит от платформы.
ERR_INVALID_HANDLE_TYPE¶
Была сделана попытка отправить неподдерживаемый «дескриптор» по каналу связи IPC дочернему процессу. Видеть subprocess.send() а также process.send() для дополнительной информации.
ERR_INVALID_HTTP_TOKEN¶
Предоставлен недопустимый токен HTTP.
ERR_INVALID_IP_ADDRESS¶
IP-адрес недействителен.
ERR_INVALID_MODULE¶
Была сделана попытка загрузить несуществующий или недействительный модуль.
ERR_INVALID_MODULE_SPECIFIER¶
Строка импортированного модуля является недопустимым URL-адресом, именем пакета или указателем подпути пакета.
ERR_INVALID_PACKAGE_CONFIG¶
Недействительный package.json файл не прошел синтаксический анализ.
ERR_INVALID_PACKAGE_TARGET¶
В package.json "exports" Поле содержит недопустимое значение сопоставления цели для попытки разрешения модуля.
ERR_INVALID_PERFORMANCE_MARK¶
При использовании Performance Timing API (perf_hooks), отметка о производительности недействительна.
ERR_INVALID_PROTOCOL¶
Недействительный options.protocol был передан http.request().
ERR_INVALID_REPL_EVAL_CONFIG¶
Оба breakEvalOnSigint а также eval параметры были установлены в REPL config, который не поддерживается.
ERR_INVALID_REPL_INPUT¶
Вход не может использоваться в REPL. Условия, при которых используется эта ошибка, описаны в REPL документация.
ERR_INVALID_RETURN_PROPERTY¶
Выбрасывается в случае, если параметр функции не предоставляет допустимое значение для одного из свойств возвращаемого объекта при выполнении.
ERR_INVALID_RETURN_PROPERTY_VALUE¶
Выбрасывается в случае, если параметр функции не предоставляет тип ожидаемого значения для одного из свойств возвращаемого объекта при выполнении.
ERR_INVALID_RETURN_VALUE¶
Вызывается в случае, если опция функции не возвращает ожидаемый тип значения при выполнении, например, когда ожидается, что функция вернет обещание.
ERR_INVALID_STATE¶
Указывает, что операция не может быть завершена из-за недопустимого состояния. Например, объект может быть уже уничтожен или может выполнять другую операцию.
ERR_INVALID_SYNC_FORK_INPUT¶
А Buffer, TypedArray, DataView или string был предоставлен как вход stdio для асинхронной вилки. См. Документацию по child_process модуль для получения дополнительной информации.
ERR_INVALID_THIS¶
Функция API Node.js была вызвана с несовместимым this ценить.
const urlSearchParams = new URLSearchParams(
'foo=bar&baz=new'
);
const buf = Buffer.alloc(1);
urlSearchParams.has.call(buf, 'foo');
// Throws a TypeError with code 'ERR_INVALID_THIS'
ERR_INVALID_TRANSFER_OBJECT¶
Недопустимый объект передачи был передан в postMessage().
ERR_INVALID_TUPLE¶
Элемент в iterable предоставлен WHATWG URLSearchParams конструктор не представлял [name, value] кортеж — то есть, если элемент не повторяется или не состоит ровно из двух элементов.
ERR_INVALID_URI¶
Передан неверный URI.
ERR_INVALID_URL¶
Недействительный URL был передан в WHATWG URL конструктор или наследие url.parse() быть разобранным. Выброшенный объект ошибки обычно имеет дополнительное свойство 'input' который содержит URL-адрес, который не удалось проанализировать.
ERR_INVALID_URL_SCHEME¶
Была сделана попытка использовать URL несовместимой схемы (протокола) для определенной цели. Он используется только в WHATWG URL API поддержка в fs модуль (который принимает только URL-адреса с 'file' схема), но может использоваться и в других API Node.js в будущем.
ERR_IPC_CHANNEL_CLOSED¶
Была сделана попытка использовать канал связи IPC, который уже был закрыт.
ERR_IPC_DISCONNECTED¶
Была сделана попытка отключить уже отключенный канал связи IPC. См. Документацию по child_process модуль для получения дополнительной информации.
ERR_IPC_ONE_PIPE¶
Была предпринята попытка создать дочерний процесс Node.js, использующий более одного канала связи IPC. См. Документацию по child_process модуль для получения дополнительной информации.
ERR_IPC_SYNC_FORK¶
Была предпринята попытка открыть канал связи IPC с помощью синхронно разветвленного процесса Node.js. См. Документацию по child_process модуль для получения дополнительной информации.
ERR_MANIFEST_ASSERT_INTEGRITY¶
Была предпринята попытка загрузить ресурс, но ресурс не соответствовал целостности, определенной в манифесте политики. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_DEPENDENCY_MISSING¶
Была предпринята попытка загрузить ресурс, но ресурс не был указан как зависимость от расположения, в котором его пытались загрузить. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_INTEGRITY_MISMATCH¶
Была сделана попытка загрузить манифест политики, но в манифесте было несколько записей для ресурса, которые не совпадали друг с другом. Обновите записи манифеста, чтобы они соответствовали, чтобы устранить эту ошибку. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_INVALID_RESOURCE_FIELD¶
Ресурс манифеста политики имел недопустимое значение для одного из полей. Обновите запись манифеста, чтобы она соответствовала, чтобы устранить эту ошибку. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_INVALID_SPECIFIER¶
Ресурс манифеста политики имел недопустимое значение для одного из сопоставлений зависимостей. Обновите запись манифеста, чтобы она соответствовала разрешению этой ошибки. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_PARSE_POLICY¶
Была предпринята попытка загрузить манифест политики, но не удалось проанализировать манифест. Документацию для политика манифесты для получения дополнительной информации.
ERR_MANIFEST_TDZ¶
Была предпринята попытка чтения из манифеста политики, но инициализация манифеста еще не произошла. Вероятно, это ошибка в Node.js.
ERR_MANIFEST_UNKNOWN_ONERROR¶
Манифест политики был загружен, но для его поведения «onerror» было неизвестно значение. Документацию для политика манифесты для получения дополнительной информации.
ERR_MEMORY_ALLOCATION_FAILED¶
Была предпринята попытка выделить память (обычно на уровне C ++), но она не удалась.
ERR_MESSAGE_TARGET_CONTEXT_UNAVAILABLE¶
Сообщение отправлено MessagePort не удалось десериализовать в целевой vm Context. Не все объекты Node.js могут быть успешно созданы в любом контексте в настоящее время, и попытки передать их с помощью postMessage() в этом случае может выйти из строя принимающая сторона.
ERR_METHOD_NOT_IMPLEMENTED¶
Метод требуется, но не реализован.
ERR_MISSING_ARGS¶
Не был передан обязательный аргумент API Node.js. Это используется только для строгого соответствия спецификации API (которая в некоторых случаях может принимать func(undefined) но нет func()). В большинстве собственных API-интерфейсов Node.js func(undefined) а также func() рассматриваются одинаково, а ERR_INVALID_ARG_TYPE вместо этого можно использовать код ошибки.
ERR_MISSING_OPTION¶
Для API-интерфейсов, которые принимают объекты параметров, некоторые параметры могут быть обязательными. Этот код выдается, если отсутствует необходимая опция.
ERR_MISSING_PASSPHRASE¶
Была сделана попытка прочитать зашифрованный ключ без указания ключевой фразы.
ERR_MISSING_PLATFORM_FOR_WORKER¶
Платформа V8, используемая этим экземпляром Node.js, не поддерживает создание рабочих. Это вызвано отсутствием поддержки Embedder для Workers. В частности, эта ошибка не возникает при использовании стандартных сборок Node.js.
ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST¶
Объект, который должен быть явно указан в transferList аргумент находится в объекте, переданном в postMessage() звоните, но не указано в transferList для этого звонка. Обычно это MessagePort.
В версиях Node.js до v15.0.0 использованный здесь код ошибки был ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST. Однако набор переносимых типов объектов был расширен, чтобы охватить больше типов, чем MessagePort.
ERR_MODULE_NOT_FOUND¶
Стабильность: 1 — экспериментальная
An Модуль ES не может быть решен.
ERR_MULTIPLE_CALLBACK¶
Обратный звонок был вызван более одного раза.
Обратный вызов почти всегда предназначен для однократного вызова, поскольку запрос может быть выполнен или отклонен, но не оба одновременно. Последнее станет возможным, если вызвать обратный вызов более одного раза.
ERR_NAPI_CONS_FUNCTION¶
При использовании Node-API, переданный конструктор не является функцией.
ERR_NAPI_INVALID_DATAVIEW_ARGS¶
Во время звонка napi_create_dataview(), данный offset находился за пределами окна просмотра данных или offset + length был больше, чем длина заданного buffer.
ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT¶
Во время звонка napi_create_typedarray()предоставленные offset не был кратен размеру элемента.
ERR_NAPI_INVALID_TYPEDARRAY_LENGTH¶
Во время звонка napi_create_typedarray(), (length * size_of_element) + byte_offset был больше, чем длина заданного buffer.
ERR_NAPI_TSFN_CALL_JS¶
Произошла ошибка при вызове части JavaScript поточно-ориентированной функции.
ERR_NAPI_TSFN_GET_UNDEFINED¶
Произошла ошибка при попытке получить код JavaScript. undefined ценить.
ERR_NAPI_TSFN_START_IDLE_LOOP¶
В основном потоке значения удаляются из очереди, связанной с поточно-ориентированной функцией, в цикле ожидания. Эта ошибка указывает на то, что произошла ошибка при попытке запустить цикл.
ERR_NAPI_TSFN_STOP_IDLE_LOOP¶
Если в очереди больше не осталось элементов, цикл простоя должен быть приостановлен. Эта ошибка указывает на то, что не удалось остановить цикл холостого хода.
ERR_NO_CRYPTO¶
Была предпринята попытка использовать функции шифрования, пока Node.js не был скомпилирован с поддержкой шифрования OpenSSL.
ERR_NO_ICU¶
Была предпринята попытка использовать функции, требующие ICU, но Node.js не был скомпилирован с поддержкой ICU.
ERR_NON_CONTEXT_AWARE_DISABLED¶
Родной аддон, не зависящий от контекста, был загружен в процессе, который их запрещает.
ERR_OUT_OF_RANGE¶
Заданное значение выходит за пределы допустимого диапазона.
ERR_PACKAGE_IMPORT_NOT_DEFINED¶
В package.json "imports" поле не определяет заданное отображение спецификатора внутреннего пакета.
ERR_PACKAGE_PATH_NOT_EXPORTED¶
В package.json "exports" не экспортирует запрошенный подпуть. Поскольку экспорт инкапсулирован, частные внутренние модули, которые не экспортируются, не могут быть импортированы через разрешение пакета, если не используется абсолютный URL-адрес.
ERR_PERFORMANCE_INVALID_TIMESTAMP¶
Для отметки производительности или показателя было предоставлено недопустимое значение метки времени.
ERR_PERFORMANCE_MEASURE_INVALID_OPTIONS¶
Предусмотрены недопустимые варианты измерения производительности.
ERR_PROTO_ACCESS¶
Доступ Object.prototype.__proto__ было запрещено использовать --disable-proto=throw. Object.getPrototypeOf а также Object.setPrototypeOf следует использовать для получения и установки прототипа объекта.
ERR_REQUIRE_ESM¶
Стабильность: 1 — экспериментальная
Была сделана попытка require() ан Модуль ES.
ERR_SCRIPT_EXECUTION_INTERRUPTED¶
Выполнение скрипта было прервано SIGINT (Например, Ctrl+C был нажат.)
ERR_SCRIPT_EXECUTION_TIMEOUT¶
Истекло время выполнения сценария, возможно, из-за ошибок в выполняемом сценарии.
ERR_SERVER_ALREADY_LISTEN¶
В server.listen() метод был вызван в то время как net.Server уже слушал. Это относится ко всем экземплярам net.Server, включая HTTP, HTTPS и HTTP / 2 Server экземпляры.
ERR_SERVER_NOT_RUNNING¶
В server.close() метод был вызван, когда net.Server не работал. Это относится ко всем экземплярам net.Server, включая HTTP, HTTPS и HTTP / 2 Server экземпляры.
ERR_SOCKET_ALREADY_BOUND¶
Была сделана попытка привязать уже связанный сокет.
ERR_SOCKET_BAD_BUFFER_SIZE¶
Был передан недопустимый (отрицательный) размер для recvBufferSize или sendBufferSize варианты в dgram.createSocket().
ERR_SOCKET_BAD_PORT¶
Функция API, ожидающая порта> = 0 и <65536, получила недопустимое значение.
ERR_SOCKET_BAD_TYPE¶
Функция API, ожидающая типа сокета (udp4 или udp6) получил недопустимое значение.
ERR_SOCKET_BUFFER_SIZE¶
При использовании dgram.createSocket(), размер получения или отправки Buffer не может быть определено.
ERR_SOCKET_CLOSED¶
Была сделана попытка работать с уже закрытым сокетом.
ERR_SOCKET_DGRAM_IS_CONNECTED¶
А dgram.connect() вызов был сделан на уже подключенном сокете.
ERR_SOCKET_DGRAM_NOT_CONNECTED¶
А dgram.disconnect() или dgram.remoteAddress() звонок был сделан на отключенной розетке.
ERR_SOCKET_DGRAM_NOT_RUNNING¶
Был сделан вызов, но подсистема UDP не работала.
ERR_SRI_PARSE¶
Строка была предоставлена для проверки целостности подресурса, но не может быть проанализирована. Проверьте формат атрибутов целостности, посмотрев на Спецификация целостности подресурсов.
ERR_STREAM_ALREADY_FINISHED¶
Был вызван метод потока, который не может быть завершен, поскольку поток был завершен.
ERR_STREAM_CANNOT_PIPE¶
Была сделана попытка позвонить stream.pipe() на Writable транслировать.
ERR_STREAM_DESTROYED¶
Был вызван метод потока, который не может быть завершен, поскольку поток был уничтожен с использованием stream.destroy().
ERR_STREAM_NULL_VALUES¶
Была сделана попытка позвонить stream.write() с null кусок.
ERR_STREAM_PREMATURE_CLOSE¶
Ошибка, возвращенная stream.finished() а также stream.pipeline(), когда поток или конвейер завершаются некорректно, без явной ошибки.
ERR_STREAM_PUSH_AFTER_EOF¶
Была сделана попытка позвонить stream.push() после null(EOF) был отправлен в поток.
ERR_STREAM_UNSHIFT_AFTER_END_EVENT¶
Была сделана попытка позвонить stream.unshift() после 'end' событие было отправлено.
ERR_STREAM_WRAP¶
Предотвращает прерывание, если строковый декодер был установлен на Socket или если декодер находится в objectMode.
const Socket = require('net').Socket;
const instance = new Socket();
instance.setEncoding('utf8');
ERR_STREAM_WRITE_AFTER_END¶
Была сделана попытка позвонить stream.write() после stream.end() был вызван.
ERR_STRING_TOO_LONG¶
Была сделана попытка создать строку длиннее максимально допустимой.
ERR_SYNTHETIC¶
Искусственный объект ошибки, используемый для захвата стека вызовов для диагностических отчетов.
ERR_SYSTEM_ERROR¶
В процессе Node.js произошла неопределенная или неспецифическая системная ошибка. Объект ошибки будет иметь err.info свойство объекта с дополнительной информацией.
ERR_TLS_CERT_ALTNAME_INVALID¶
При использовании TLS имя хоста / IP-адрес однорангового узла не соответствует ни одному из subjectAltNames в его сертификате.
ERR_TLS_DH_PARAM_SIZE¶
При использовании TLS параметр, предлагаемый для алгоритма Диффи-Хеллмана (DH) протокол согласования ключей слишком мал. По умолчанию длина ключа должна быть больше или равна 1024 битам, чтобы избежать уязвимостей, хотя настоятельно рекомендуется использовать 2048 бит или больше для большей безопасности.
ERR_TLS_HANDSHAKE_TIMEOUT¶
Время ожидания подтверждения TLS / SSL истекло. В этом случае сервер также должен прервать соединение.
ERR_TLS_INVALID_CONTEXT¶
Контекст должен быть SecureContext.
ERR_TLS_INVALID_PROTOCOL_METHOD¶
Указанный secureProtocol метод недействителен. Он либо неизвестен, либо отключен, потому что небезопасен.
ERR_TLS_INVALID_PROTOCOL_VERSION¶
Допустимые версии протокола TLS: 'TLSv1', 'TLSv1.1', или 'TLSv1.2'.
ERR_TLS_INVALID_STATE¶
Сокет TLS должен быть подключен и надежно установлен. Перед продолжением убедитесь, что «безопасное» событие запущено.
ERR_TLS_PROTOCOL_VERSION_CONFLICT¶
Попытка установить протокол TLS minVersion или maxVersion конфликтует с попыткой установить secureProtocol явно. Используйте тот или иной механизм.
ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED¶
Не удалось установить подсказку идентификатора PSK. Подсказка может быть слишком длинной.
ERR_TLS_RENEGOTIATION_DISABLED¶
Была сделана попытка повторно согласовать TLS на экземпляре сокета с отключенным TLS.
ERR_TLS_REQUIRED_SERVER_NAME¶
При использовании TLS server.addContext() был вызван без указания имени хоста в первом параметре.
ERR_TLS_SESSION_ATTACK¶
Обнаружено чрезмерное количество повторных согласований TLS, что является потенциальным вектором атак типа «отказ в обслуживании».
ERR_TLS_SNI_FROM_SERVER¶
Была предпринята попытка выдать указание имени сервера из сокета на стороне сервера TLS, который действителен только для клиента.
ERR_TRACE_EVENTS_CATEGORY_REQUIRED¶
В trace_events.createTracing() требуется по крайней мере одна категория событий трассировки.
ERR_TRACE_EVENTS_UNAVAILABLE¶
В trace_events модуль не может быть загружен, потому что Node.js был скомпилирован с --without-v8-platform флаг.
ERR_TRANSFORM_ALREADY_TRANSFORMING¶
А Transform поток завершился, пока он все еще преобразовывался.
ERR_TRANSFORM_WITH_LENGTH_0¶
А Transform поток закончился с данными, все еще находящимися в буфере записи.
ERR_TTY_INIT_FAILED¶
Инициализация TTY не удалась из-за системной ошибки.
ERR_UNAVAILABLE_DURING_EXIT¶
Функция была вызвана в process.on('exit') обработчик, который не должен вызываться внутри process.on('exit') обработчик.
ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET¶
process.setUncaughtExceptionCaptureCallback() был вызван дважды, без предварительного сброса обратного вызова на null.
Эта ошибка предназначена для предотвращения случайной перезаписи обратного вызова, зарегистрированного из другого модуля.
ERR_UNESCAPED_CHARACTERS¶
Получена строка, содержащая неэкранированные символы.
ERR_UNHANDLED_ERROR¶
Произошла необработанная ошибка (например, когда 'error' событие испускается EventEmitter но 'error' обработчик не зарегистрирован).
ERR_UNKNOWN_BUILTIN_MODULE¶
Используется для определения определенного вида внутренней ошибки Node.js, которая обычно не должна запускаться кодом пользователя. Экземпляры этой ошибки указывают на внутреннюю ошибку в самом двоичном файле Node.js.
ERR_UNKNOWN_CREDENTIAL¶
Был передан несуществующий идентификатор группы или пользователя Unix.
ERR_UNKNOWN_ENCODING¶
В API передан неверный или неизвестный параметр кодировки.
ERR_UNKNOWN_FILE_EXTENSION¶
Стабильность: 1 — экспериментальная
Была сделана попытка загрузить модуль с неизвестным или неподдерживаемым расширением файла.
ERR_UNKNOWN_MODULE_FORMAT¶
Стабильность: 1 — экспериментальная
Была сделана попытка загрузить модуль с неизвестным или неподдерживаемым форматом.
ERR_UNKNOWN_SIGNAL¶
Неверный или неизвестный сигнал процесса был передан API, ожидающему действительного сигнала (например, subprocess.kill()).
ERR_UNSUPPORTED_DIR_IMPORT¶
import URL-адрес каталога не поддерживается. Вместо, Самостоятельная ссылка на пакет, используя его имя а также определить настраиваемый подпуть в "exports" поле package.json файл.
import './'; // unsupported
import './index.js'; // supported
import 'package-name'; // supported
ERR_UNSUPPORTED_ESM_URL_SCHEME¶
import со схемами URL, отличными от file а также data не поддерживается.
ERR_VALID_PERFORMANCE_ENTRY_TYPE¶
При использовании Performance Timing API (perf_hooks) допустимые типы записей производительности не найдены.
ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING¶
Обратный вызов динамического импорта не указан.
ERR_VM_MODULE_ALREADY_LINKED¶
Модуль, который пытались связать, не подходит для связывания по одной из следующих причин:
- Он уже был связан (
linkingStatusявляется'linked') - Это связано (
linkingStatusявляется'linking') - Не удалось установить связь для этого модуля (
linkingStatusявляется'errored')
ERR_VM_MODULE_CACHED_DATA_REJECTED¶
В cachedData Параметр, переданный конструктору модуля, недопустим.
ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA¶
Кэшированные данные не могут быть созданы для модулей, которые уже были оценены.
ERR_VM_MODULE_DIFFERENT_CONTEXT¶
Модуль, возвращаемый функцией компоновщика, находится в другом контексте, чем родительский модуль. Связанные модули должны иметь общий контекст.
ERR_VM_MODULE_LINKING_ERRORED¶
Функция компоновщика вернула модуль, для которого не удалось выполнить связывание.
ERR_VM_MODULE_LINK_FAILURE¶
Модуль не удалось связать из-за сбоя.
ERR_VM_MODULE_NOT_MODULE¶
Выполненное значение обещания связывания не является vm.Module объект.
ERR_VM_MODULE_STATUS¶
Текущий статус модуля не позволяет выполнить эту операцию. Конкретный смысл ошибки зависит от конкретной функции.
ERR_WASI_ALREADY_STARTED¶
Экземпляр WASI уже запущен.
ERR_WASI_NOT_STARTED¶
Экземпляр WASI не запущен.
ERR_WORKER_INIT_FAILED¶
В Worker Ошибка инициализации.
ERR_WORKER_INVALID_EXEC_ARGV¶
В execArgv вариант передан в Worker конструктор содержит недопустимые флаги.
ERR_WORKER_NOT_RUNNING¶
Операция завершилась неудачно, потому что Worker экземпляр в настоящее время не запущен.
ERR_WORKER_OUT_OF_MEMORY¶
В Worker Экземпляр остановлен, поскольку достиг предела памяти.
ERR_WORKER_PATH¶
Путь для основного скрипта рабочего не является ни абсолютным, ни относительным путем, начинающимся с ./ или ../.
ERR_WORKER_UNSERIALIZABLE_ERROR¶
Все попытки сериализации неперехваченного исключения из рабочего потока завершились неудачно.
ERR_WORKER_UNSUPPORTED_OPERATION¶
Запрошенная функциональность не поддерживается в рабочих потоках.
ERR_ZLIB_INITIALIZATION_FAILED¶
Создание zlib сбой объекта из-за неправильной конфигурации.
Получено слишком много данных заголовка HTTP. Для защиты от злонамеренных или неправильно настроенных клиентов, если получено более 8 КБ данных HTTP-заголовка, анализ HTTP будет прерван без создания объекта запроса или ответа, и Error с этим кодом будет выпущен.
HPE_UNEXPECTED_CONTENT_LENGTH¶
Сервер отправляет как Content-Length заголовок и Transfer-Encoding: chunked.
Transfer-Encoding: chunked позволяет серверу поддерживать постоянное соединение HTTP для динамически генерируемого контента. В этом случае Content-Length Заголовок HTTP использовать нельзя.
Использовать Content-Length или Transfer-Encoding: chunked.
MODULE_NOT_FOUND¶
Не удалось разрешить файл модуля при попытке require() или import операция.
Устаревшие коды ошибок Node.js¶
Стабильность: 0 — Не рекомендуется. Эти коды ошибок либо несовместимы, либо были удалены.
ERR_CANNOT_TRANSFER_OBJECT¶
Значение, переданное в postMessage() содержит объект, который не поддерживается для передачи.
ERR_CRYPTO_HASH_DIGEST_NO_UTF16¶
Кодировка UTF-16 использовалась с hash.digest(). В то время как hash.digest() метод позволяет encoding аргумент, который должен быть передан, в результате чего метод возвращает строку, а не Buffer, кодировка UTF-16 (например, ucs или utf16le) не поддерживается.
ERR_HTTP2_FRAME_ERROR¶
Используется при сбое отправки отдельного кадра в сеансе HTTP / 2.
Используется, когда ожидается объект заголовков HTTP / 2.
Используется, когда в сообщении HTTP / 2 отсутствует требуемый заголовок.
Информационные заголовки HTTP / 2 должны отправляться только прежний позвонить в Http2Stream.prototype.respond() метод.
ERR_HTTP2_STREAM_CLOSED¶
Используется, когда действие было выполнено над уже закрытым потоком HTTP / 2.
ERR_HTTP_INVALID_CHAR¶
Используется, когда в сообщении статуса ответа HTTP (фраза причины) обнаружен недопустимый символ.
ERR_INDEX_OUT_OF_RANGE¶
Данный индекс был вне допустимого диапазона (например, отрицательные смещения).
ERR_INVALID_OPT_VALUE¶
В объект опций было передано недопустимое или неожиданное значение.
ERR_INVALID_OPT_VALUE_ENCODING¶
Передана неверная или неизвестная кодировка файла.
ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST¶
Этот код ошибки был заменен на ERR_MISSING_TRANSFERABLE_IN_TRANSFER_LIST в Node.js v15.0.0, потому что он больше не точен, поскольку теперь существуют и другие типы переносимых объектов.
ERR_NAPI_CONS_PROTOTYPE_OBJECT¶
Используется Node-API когда Constructor.prototype не объект.
ERR_NO_LONGER_SUPPORTED¶
API Node.js был вызван неподдерживаемым способом, например Buffer.write(string, encoding, offset[, length]).
ERR_OPERATION_FAILED¶
Не удалось выполнить операцию. Обычно это используется, чтобы сигнализировать об общем сбое асинхронной операции.
ERR_OUTOFMEMORY¶
Обычно используется для определения того, что операция вызвала нехватку памяти.
ERR_PARSE_HISTORY_DATA¶
В repl модулю не удалось проанализировать данные из файла истории REPL.
ERR_SOCKET_CANNOT_SEND¶
Данные не могут быть отправлены через сокет.
ERR_STDERR_CLOSE¶
Была сделана попытка закрыть process.stderr транслировать. По замыслу Node.js не позволяет stdout или stderr потоки должны быть закрыты кодом пользователя.
ERR_STDOUT_CLOSE¶
Была сделана попытка закрыть process.stdout транслировать. По замыслу Node.js не позволяет stdout или stderr потоки должны быть закрыты кодом пользователя.
ERR_STREAM_READ_NOT_IMPLEMENTED¶
Используется, когда делается попытка использовать читаемый поток, который не реализован readable._read().
ERR_TLS_RENEGOTIATION_FAILED¶
Используется, когда запрос на повторное согласование TLS завершился ошибкой неспецифическим образом.
ERR_TRANSFERRING_EXTERNALIZED_SHAREDARRAYBUFFER¶
А SharedArrayBuffer чья память не управляется механизмом JavaScript или Node.js. во время сериализации. Такой SharedArrayBuffer не может быть сериализован.
Это может произойти только тогда, когда нативные аддоны создают SharedArrayBuffers в «внешнем» режиме или поместите существующий SharedArrayBuffer во внешний режим.
ERR_UNKNOWN_STDIN_TYPE¶
Была предпринята попытка запустить процесс Node.js с неизвестным stdin тип файла. Эта ошибка обычно указывает на ошибку в самом Node.js, хотя пользовательский код может вызвать ее.
ERR_UNKNOWN_STREAM_TYPE¶
Была предпринята попытка запустить процесс Node.js с неизвестным stdout или stderr тип файла. Эта ошибка обычно указывает на ошибку в самом Node.js, хотя пользовательский код может вызвать ее.
ERR_V8BREAKITERATOR¶
V8 BreakIterator API использовался, но не установлен полный набор данных ICU.
ERR_VALUE_OUT_OF_RANGE¶
Используется, когда заданное значение выходит за пределы допустимого диапазона.
ERR_VM_MODULE_NOT_LINKED¶
Перед созданием экземпляра модуль должен быть успешно связан.
ERR_WORKER_UNSUPPORTED_EXTENSION¶
Имя пути, используемое для основного сценария рабочего, имеет неизвестное расширение файла.
ERR_ZLIB_BINDING_CLOSED¶
Используется, когда делается попытка использовать zlib объект после того, как он уже был закрыт.
ERR_CPU_USAGE¶
Родной звонок от process.cpuUsage не может быть обработано.
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:
- message: A string value that carries the error message
- name: The type of error that occurred (We’ll dive deep into this in the next section)
- 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:

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:

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 message will usually indicate what is wrong with your code. Once you make the changes, it will be resolved.

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:

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

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:

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:

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:

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 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:

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:

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 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:

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:
- Add the
crossoriginattribute in the script tag. - Set the correct
Access-Control-Allow-Originheader on the server hosting the script. - [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
throwanything, including numbers, strings, andErrorobjects. - 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:

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:

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:

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:

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:
- message: A string value that carries the error message
- name: The type of error that occurred (We’ll dive deep into this in the next section)
- 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:

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:

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 message will usually indicate what is wrong with your code. Once you make the changes, it will be resolved.

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:

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

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:

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:

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:

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 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:

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:

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 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:

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:
- Add the
crossoriginattribute in the script tag. - Set the correct
Access-Control-Allow-Originheader on the server hosting the script. - [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
throwanything, including numbers, strings, andErrorobjects. - 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:

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:

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:

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:

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.