{ "source": "doc/api/errors.md", "classes": [ { "textRaw": "Class: Error", "type": "class", "name": "Error", "desc": "
A generic JavaScript Error
object that does not denote any specific\ncircumstance of why the error occurred. Error
objects capture a "stack trace"\ndetailing the point in the code at which the Error
was instantiated, and may\nprovide a text description of the error.
All errors generated by Node.js, including all System and JavaScript errors,\nwill either be instances of, or inherit from, the Error
class.
Creates a .stack
property on targetObject
, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace()
was called.
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack; // similar to `new Error().stack`\n
\nThe first line of the trace, instead of being prefixed with ErrorType:\nmessage
, will be the result of calling targetObject.toString()
.
The optional constructorOpt
argument accepts a function. If given, all frames\nabove constructorOpt
, including constructorOpt
, will be omitted from the\ngenerated stack trace.
The constructorOpt
argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:
function MyError() {\n Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
\n"
}
],
"properties": [
{
"textRaw": "`stackTraceLimit` {number} ",
"type": "number",
"name": "stackTraceLimit",
"desc": "The Error.stackTraceLimit
property specifies the number of stack frames\ncollected by a stack trace (whether generated by new Error().stack
or\nError.captureStackTrace(obj)
).
The default value is 10
but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.
\n", "properties": [ { "textRaw": "`code` {string} ", "type": "string", "name": "code", "desc": "The error.code
property is a string label that identifies the kind of error.\nSee Node.js Error Codes for details about specific codes.
The error.message
property is the string description of the error as set by\ncalling new Error(message)
. The message
passed to the constructor will also\nappear in the first line of the stack trace of the Error
, however changing\nthis property after the Error
object is created may not change the first\nline of the stack trace (for example, when error.stack
is read before this\nproperty is changed).
const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
\n"
}
]
},
{
"textRaw": "`stack` {string} ",
"type": "string",
"name": "stack",
"desc": "The error.stack
property is a string describing the point in the code at which\nthe Error
was instantiated.
For example:
\nError: Things keep happening!\n at /home/gbusey/file.js:525:2\n at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n at increaseSynergy (/home/gbusey/actors.js:701:6)\n
\nThe first line is formatted as <error class name>: <error message>
, and\nis followed by a series of stack frames (each line beginning with "at ").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.
It is important to note that frames are only generated for JavaScript\nfunctions. If, for example, execution synchronously passes through a C++ addon\nfunction called cheetahify
, which itself calls a JavaScript function, the\nframe representing the cheetahify
call will not be present in the stack\ntraces:
const cheetahify = require('./native-binding.node');\n\nfunction makeFaster() {\n // cheetahify *synchronously* calls speedy.\n cheetahify(function speedy() {\n throw new Error('oh no!');\n });\n}\n\nmakeFaster(); // will throw:\n // /home/gbusey/file.js:6\n // throw new Error('oh no!');\n // ^\n // Error: oh no!\n // at speedy (/home/gbusey/file.js:6:11)\n // at makeFaster (/home/gbusey/file.js:5:3)\n // at Object.<anonymous> (/home/gbusey/file.js:10:1)\n // at Module._compile (module.js:456:26)\n // at Object.Module._extensions..js (module.js:474:10)\n // at Module.load (module.js:356:32)\n // at Function.Module._load (module.js:312:12)\n // at Function.Module.runMain (module.js:497:10)\n // at startup (node.js:119:16)\n // at node.js:906:3\n
\nThe location information will be one of:
\nnative
, if the frame represents a call internal to V8 (as in [].forEach
).plain-filename.js:line:column
, if the frame represents a call internal\n to Node.js./absolute/path/to/file.js:line:column
, if the frame represents a call in\na user program, or its dependencies.The string representing the stack trace is lazily generated when the\nerror.stack
property is accessed.
The number of frames captured by the stack trace is bounded by the smaller of\nError.stackTraceLimit
or the number of available frames on the current event\nloop tick.
System-level errors are generated as augmented Error
instances, which are\ndetailed here.
Creates a new Error
object and sets the error.message
property to the\nprovided text message. If an object is passed as message
, the text message\nis generated by calling message.toString()
. The error.stack
property will\nrepresent the point in the code at which new Error()
was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit
, whichever is smaller.
Creates a new Error
object and sets the error.message
property to the\nprovided text message. If an object is passed as message
, the text message\nis generated by calling message.toString()
. The error.stack
property will\nrepresent the point in the code at which new Error()
was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit
, whichever is smaller.
A subclass of Error
that indicates that a provided argument was not within the\nset or range of acceptable values for a function; whether that is a numeric\nrange, or outside the set of options for a given function parameter.
For example:
\nrequire('net').connect(-1);\n // throws "RangeError: "port" option should be >= 0 and < 65536: -1"\n
\nNode.js will generate and throw RangeError
instances immediately as a form\nof argument validation.
A subclass of Error
that indicates that an attempt is being made to access a\nvariable that is not defined. Such errors commonly indicate typos in code, or\nan otherwise broken program.
While client code may generate and propagate these errors, in practice, only V8\nwill do so.
\ndoesNotExist;\n // throws ReferenceError, doesNotExist is not a variable in this program.\n
\nUnless an application is dynamically generating and running code,\nReferenceError
instances should always be considered a bug in the code\nor its dependencies.
A subclass of Error
that indicates that a program is not valid JavaScript.\nThese errors may only be generated and propagated as a result of code\nevaluation. Code evaluation may happen as a result of eval
, Function
,\nrequire
, or vm. These errors are almost always indicative of a broken\nprogram.
try {\n require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n // err will be a SyntaxError\n}\n
\nSyntaxError
instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.
A subclass of Error
that indicates that a provided argument is not an\nallowable type. For example, passing a function to a parameter which expects a\nstring would be considered a TypeError.
require('url').parse(() => { });\n // throws TypeError, since it expected a string\n
\nNode.js will generate and throw TypeError
instances immediately as a form\nof argument validation.
Applications running in Node.js will generally experience four categories of\nerrors:
\neval()
fails.assert
module.All JavaScript and System errors raised by Node.js inherit from, or are\ninstances of, the standard JavaScript {Error} class and are guaranteed\nto provide at least the properties available on that class.
\n", "miscs": [ { "textRaw": "Error Propagation and Interception", "name": "Error Propagation and Interception", "type": "misc", "desc": "Node.js supports several mechanisms for propagating and handling errors that\noccur while an application is running. How these errors are reported and\nhandled depends entirely on the type of Error and the style of the API that is\ncalled.
\nAll JavaScript errors are handled as exceptions that immediately generate\nand throw an error using the standard JavaScript throw
mechanism. These\nare handled using the try / catch
construct provided by the\nJavaScript language.
// Throws with a ReferenceError because z is undefined\ntry {\n const m = 1;\n const n = m + z;\n} catch (err) {\n // Handle the error here.\n}\n
\nAny use of the JavaScript throw
mechanism will raise an exception that\nmust be handled using try / catch
or the Node.js process will exit\nimmediately.
With few exceptions, Synchronous APIs (any blocking method that does not\naccept a callback
function, such as fs.readFileSync
), will use throw
\nto report errors.
Errors that occur within Asynchronous APIs may be reported in multiple ways:
\ncallback
function will accept an\nError
object passed as the first argument to that function. If that first\nargument is not null
and is an instance of Error
, then an error occurred\nthat should be handled. const fs = require('fs');\n fs.readFile('a file that does not exist', (err, data) => {\n if (err) {\n console.error('There was an error reading the file!', err);\n return;\n }\n // Otherwise handle the data\n });\n
\nWhen an asynchronous method is called on an object that is an EventEmitter
,\nerrors can be routed to that object's 'error'
event.
const net = require('net');\nconst connection = net.connect('localhost');\n\n// Adding an 'error' event handler to a stream:\nconnection.on('error', (err) => {\n // If the connection is reset by the server, or if it can't\n // connect at all, or on any sort of error encountered by\n // the connection, the error will be sent here.\n console.error(err);\n});\n\nconnection.pipe(process.stdout);\n
\nA handful of typically asynchronous methods in the Node.js API may still\nuse the throw
mechanism to raise exceptions that must be handled using\ntry / catch
. There is no comprehensive list of such methods; please\nrefer to the documentation of each method to determine the appropriate\nerror handling mechanism required.
The use of the 'error'
event mechanism is most common for stream-based\nand event emitter-based APIs, which themselves represent a series of\nasynchronous operations over time (as opposed to a single operation that may\npass or fail).
For all EventEmitter
objects, if an 'error'
event handler is not\nprovided, the error will be thrown, causing the Node.js process to report an\nunhandled exception and crash unless either: The domain
module is\nused appropriately or a handler has been registered for the\nprocess.on('uncaughtException')
event.
const EventEmitter = require('events');\nconst ee = new EventEmitter();\n\nsetImmediate(() => {\n // This will crash the process because no 'error' event\n // handler has been added.\n ee.emit('error', new Error('This will crash'));\n});\n
\nErrors generated in this way cannot be intercepted using try / catch
as\nthey are thrown after the calling code has already exited.
Developers must refer to the documentation for each method to determine\nexactly how errors raised by those methods are propagated.
\n", "miscs": [ { "textRaw": "Node.js style callbacks", "name": "Node.js style callbacks", "type": "misc", "desc": "Most asynchronous methods exposed by the Node.js core API follow an idiomatic\npattern referred to as a "Node.js style callback". With this pattern, a\ncallback function is passed to the method as an argument. When the operation\neither completes or an error is raised, the callback function is called with\nthe Error object (if any) passed as the first argument. If no error was raised,\nthe first argument will be passed as null
.
const fs = require('fs');\n\nfunction nodeStyleCallback(err, data) {\n if (err) {\n console.error('There was an error', err);\n return;\n }\n console.log(data);\n}\n\nfs.readFile('/some/file/that/does-not-exist', nodeStyleCallback);\nfs.readFile('/some/file/that/does-exist', nodeStyleCallback);\n
\nThe JavaScript try / catch
mechanism cannot be used to intercept errors\ngenerated by asynchronous APIs. A common mistake for beginners is to try to\nuse throw
inside a Node.js style callback:
// THIS WILL NOT WORK:\nconst fs = require('fs');\n\ntry {\n fs.readFile('/some/file/that/does-not-exist', (err, data) => {\n // mistaken assumption: throwing here...\n if (err) {\n throw err;\n }\n });\n} catch (err) {\n // This will not catch the throw!\n console.error(err);\n}\n
\nThis will not work because the callback function passed to fs.readFile()
is\ncalled asynchronously. By the time the callback has been called, the\nsurrounding code (including the try { } catch (err) { }
block will have\nalready exited. Throwing an error inside the callback can crash the Node.js\nprocess in most cases. If domains are enabled, or a handler has been\nregistered with process.on('uncaughtException')
, such errors can be\nintercepted.
A JavaScript exception is a value that is thrown as a result of an invalid\noperation or as the target of a throw
statement. While it is not required\nthat these values are instances of Error
or classes which inherit from\nError
, all exceptions thrown by Node.js or the JavaScript runtime will be\ninstances of Error.
Some exceptions are unrecoverable at the JavaScript layer. Such exceptions\nwill always cause the Node.js process to crash. Examples include assert()
\nchecks or abort()
calls in the C++ layer.
System errors are generated when exceptions occur within the program's\nruntime environment. Typically, these are operational errors that occur\nwhen an application violates an operating system constraint such as attempting\nto read a file that does not exist or when the user does not have sufficient\npermissions.
\nSystem errors are typically generated at the syscall level: an exhaustive list\nof error codes and their meanings is available by running man 2 intro
or\nman 3 errno
on most Unices; or online.
In Node.js, system errors are represented as augmented Error
objects with\nadded properties.
The error.code
property is a string representing the error code, which is\ntypically E
followed by a sequence of capital letters.
The error.errno
property is a number or a string.\nThe number is a negative value which corresponds to the error code defined\nin libuv Error handling
. See uv-errno.h header file\n(deps/uv/include/uv-errno.h
in the Node.js source tree) for details. In case\nof a string, it is the same as error.code
.
The error.syscall
property is a string describing the syscall that failed.
When present (e.g. in fs
or child_process
), the error.path
property is a\nstring containing a relevant invalid pathname.
When present (e.g. in net
or dgram
), the error.address
property is a\nstring describing the address to which the connection failed.
When present (e.g. in net
or dgram
), the error.port
property is a number\nrepresenting the connection's port that is not available.
This list is not exhaustive, but enumerates many of the common system\nerrors encountered when writing a Node.js program. An exhaustive list may be\nfound here.
\nEACCES
(Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.
EADDRINUSE
(Address already in use): An attempt to bind a server\n(net
, http
, or https
) to a local address failed due to\nanother server on the local system already occupying that address.
ECONNREFUSED
(Connection refused): No connection could be made because the\ntarget machine actively refused it. This usually results from trying to\nconnect to a service that is inactive on the foreign host.
ECONNRESET
(Connection reset by peer): A connection was forcibly closed by\na peer. This normally results from a loss of the connection on the remote\nsocket due to a timeout or reboot. Commonly encountered via the http
\nand net
modules.
EEXIST
(File exists): An existing file was the target of an operation that\nrequired that the target not exist.
EISDIR
(Is a directory): An operation expected a file, but the given\npathname was a directory.
EMFILE
(Too many open files in system): Maximum number of\nfile descriptors allowable on the system has been reached, and\nrequests for another descriptor cannot be fulfilled until at least one\nhas been closed. This is encountered when opening many files at once in\nparallel, especially on systems (in particular, macOS) where there is a low\nfile descriptor limit for processes. To remedy a low limit, run\nulimit -n 2048
in the same shell that will run the Node.js process.
ENOENT
(No such file or directory): Commonly raised by fs
operations\nto indicate that a component of the specified pathname does not exist -- no\nentity (file or directory) could be found by the given path.
ENOTDIR
(Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir
.
ENOTEMPTY
(Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory -- usually fs.unlink
.
EPERM
(Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.
EPIPE
(Broken pipe): A write on a pipe, socket, or FIFO for which there is\nno process to read the data. Commonly encountered at the net
and\nhttp
layers, indicative that the remote side of the stream being\nwritten to has been closed.
ETIMEDOUT
(Operation timed out): A connect or send request failed because\nthe connected party did not properly respond after a period of time. Usually\nencountered by http
or net
-- often a sign that a socket.end()
\nwas not properly called.
The 'ERR_ARG_NOT_ITERABLE'
error code is used generically to identify that an\niterable argument (i.e. a value that works with for...of
loops) is required,\nbut not provided to a Node.js API.
The 'ERR_INVALID_ARG_TYPE'
error code is used generically to identify that\nan argument of the wrong type has been passed to a Node.js API.
The 'ERR_INVALID_CALLBACK'
error code is used generically to identify that\na callback function is required and has not been provided to a Node.js API.
An error with the 'ERR_INVALID_FILE_URL_HOST'
code may be thrown when a\nNode.js API that consumes file:
URLs (such as certain functions in the\nfs
module) encounters a file URL with an incompatible host. Currently,\nthis situation can only occur on Unix-like systems, where only localhost
or\nan empty host is supported.
An error with the 'ERR_INVALID_FILE_URL_PATH'
code may be thrown when a\nNode.js API that consumes file:
URLs (such as certain functions in the\nfs
module) encounters a file URL with an incompatible path. The exact\nsemantics for determining whether a path can be used is platform-dependent.
The 'ERR_INVALID_HANDLE_TYPE
' error code is used when an attempt is made to\nsend an unsupported "handle" over an IPC communication channel to a child\nprocess. See child.send()
and process.send()
for more information.
The 'ERR_INVALID_OPT_VALUE'
error code is used generically to identify when\nan invalid or unexpected value has been passed in an options object.
The 'ERR_INVALID_SYNC_FORK_INPUT'
error code is used when a Buffer
,\nUint8Array
or string
is provided as stdio input to a synchronous\nfork. See the documentation for the child_process
\nmodule for more information.
The 'ERR_INVALID_THIS'
error code is used generically to identify that a\nNode.js API function is called with an incompatible this
value.
Example:
\nconst { URLSearchParams } = require('url');\nconst urlSearchParams = new URLSearchParams('foo=bar&baz=new');\n\nconst buf = Buffer.alloc(1);\nurlSearchParams.has.call(buf, 'foo');\n // Throws a TypeError with code 'ERR_INVALID_THIS'\n
\n\n",
"type": "module",
"displayName": "ERR_INVALID_THIS"
},
{
"textRaw": "ERR_INVALID_TUPLE",
"name": "err_invalid_tuple",
"desc": "An error with code 'ERR_INVALID_TUPLE'
is thrown when an element in the\niterable
provided to the WHATWG URLSearchParams
\nconstructor does not represent a [name,\nvalue]
tuple – that is, if an element is not iterable, or does not consist of\nexactly two elements.
An error using the 'ERR_INVALID_URL'
code is thrown when an invalid URL is\npassed to the WHATWG URL
constructor to\nbe parsed. The thrown error object typically has an additional property\n'input'
that contains the URL that failed to parse.
The code 'ERR_INVALID_URL_SCHEME'
is used generically to signify an attempt\nto use a URL of an incompatible scheme (aka protocol) for a specific purpose.\nIt is currently only used in the WHATWG URL API support in the fs
\nmodule (which only accepts URLs with 'file'
scheme), but may be used in other\nNode.js APIs as well in the future.
The 'ERR_IPC_CHANNEL_CLOSED'
error code is used when an attempt is made to use\nan IPC communication channel that has already been closed.
The 'ERR_IPC_DISCONNECTED'
error code is used when an attempt is made to\ndisconnect an already disconnected IPC communication channel between two\nNode.js processes. See the documentation for the\nchild_process
module for more information.
The 'ERR_IPC_ONE_PIPE'
error code is used when an attempt is made to create\na child Node.js process using more than one IPC communication channel.\nSee the documentation for the child_process
\nmodule for more information.
The 'ERR_IPC_SYNC_FORK'
error code is used when an attempt is made to open\nan IPC communication channel with a synchronous forked Node.js process.\nSee the documentation for the child_process
\nmodule for more information.
The 'ERR_MISSING_ARGS'
error code is a generic error code for instances where\na required argument of a Node.js API is not passed. This is currently only used\nin the WHATWG URL API for strict compliance with the specification (which\nin some cases may accept func(undefined)
but not func()
). In most native\nNode.js APIs, func(undefined)
and func()
are treated identically, and the\nERR_INVALID_ARG_TYPE
error code may be used instead.
An error using the 'ERR_SOCKET_ALREADY_BOUND'
code is thrown when an attempt\nis made to bind a socket that has already been bound.
An error using the 'ERR_SOCKET_BAD_PORT'
code is thrown when an API\nfunction expecting a port > 0 and < 65536 receives an invalid value.
An error using the 'ERR_SOCKET_BAD_TYPE'
code is thrown when an API\nfunction expecting a socket type (udp4
or udp6
) receives an invalid value.
An error using the 'ERR_SOCKET_CANNOT_SEND'
code is thrown when data\ncannot be sent on a socket.
An error using the 'ERR_SOCKET_DGRAM_NOT_RUNNING'
code is thrown\nwhen a call is made and the UDP subsystem is not running.
An error using the 'ERR_STDERR_CLOSE'
code is thrown specifically when an\nattempt is made to close the process.stderr
stream. By design, Node.js does\nnot allow stdout
or stderr
Streams to be closed by user code.
An error using the 'ERR_STDOUT_CLOSE'
code is thrown specifically when an\nattempt is made to close the process.stdout
stream. By design, Node.js does\nnot allow stdout
or stderr
Streams to be closed by user code.
The 'ERR_UNKNOWN_BUILTIN_MODULE'
error code is used to identify a specific\nkind of internal Node.js error that should not typically be triggered by user\ncode. Instances of this error point to an internal bug within the Node.js\nbinary itself.
The 'ERR_UNKNOWN_SIGNAL
' error code is used when an invalid or unknown\nprocess signal is passed to an API expecting a valid signal (such as\nchild.kill()
).
An error using the 'ERR_UNKNOWN_STDIN_TYPE'
code is thrown specifically when\nan attempt is made to launch a Node.js process with an unknown stdin
file\ntype. Errors of this kind cannot typically be caused by errors in user code,\nalthough it is not impossible. Occurrences of this error are most likely an\nindication of a bug within Node.js itself.
An error using the 'ERR_UNKNOWN_STREAM_TYPE'
code is thrown specifically when\nan attempt is made to launch a Node.js process with an unknown stdout
or\nstderr
file type. Errors of this kind cannot typically be caused by errors\nin user code, although it is not impossible. Occurrences of this error are most\nlikely an indication of a bug within Node.js itself.
A generic JavaScript Error
object that does not denote any specific\ncircumstance of why the error occurred. Error
objects capture a "stack trace"\ndetailing the point in the code at which the Error
was instantiated, and may\nprovide a text description of the error.
All errors generated by Node.js, including all System and JavaScript errors,\nwill either be instances of, or inherit from, the Error
class.
Creates a .stack
property on targetObject
, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace()
was called.
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack; // similar to `new Error().stack`\n
\nThe first line of the trace, instead of being prefixed with ErrorType:\nmessage
, will be the result of calling targetObject.toString()
.
The optional constructorOpt
argument accepts a function. If given, all frames\nabove constructorOpt
, including constructorOpt
, will be omitted from the\ngenerated stack trace.
The constructorOpt
argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:
function MyError() {\n Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame, and retain all frames below it.\nnew MyError().stack;\n
\n"
}
],
"properties": [
{
"textRaw": "`stackTraceLimit` {number} ",
"type": "number",
"name": "stackTraceLimit",
"desc": "The Error.stackTraceLimit
property specifies the number of stack frames\ncollected by a stack trace (whether generated by new Error().stack
or\nError.captureStackTrace(obj)
).
The default value is 10
but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.
\n", "properties": [ { "textRaw": "`code` {string} ", "type": "string", "name": "code", "desc": "The error.code
property is a string label that identifies the kind of error.\nSee Node.js Error Codes for details about specific codes.
The error.message
property is the string description of the error as set by\ncalling new Error(message)
. The message
passed to the constructor will also\nappear in the first line of the stack trace of the Error
, however changing\nthis property after the Error
object is created may not change the first\nline of the stack trace (for example, when error.stack
is read before this\nproperty is changed).
const err = new Error('The message');\nconsole.error(err.message);\n// Prints: The message\n
\n"
}
]
},
{
"textRaw": "`stack` {string} ",
"type": "string",
"name": "stack",
"desc": "The error.stack
property is a string describing the point in the code at which\nthe Error
was instantiated.
For example:
\nError: Things keep happening!\n at /home/gbusey/file.js:525:2\n at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n at increaseSynergy (/home/gbusey/actors.js:701:6)\n
\nThe first line is formatted as <error class name>: <error message>
, and\nis followed by a series of stack frames (each line beginning with "at ").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.
It is important to note that frames are only generated for JavaScript\nfunctions. If, for example, execution synchronously passes through a C++ addon\nfunction called cheetahify
, which itself calls a JavaScript function, the\nframe representing the cheetahify
call will not be present in the stack\ntraces:
const cheetahify = require('./native-binding.node');\n\nfunction makeFaster() {\n // cheetahify *synchronously* calls speedy.\n cheetahify(function speedy() {\n throw new Error('oh no!');\n });\n}\n\nmakeFaster(); // will throw:\n // /home/gbusey/file.js:6\n // throw new Error('oh no!');\n // ^\n // Error: oh no!\n // at speedy (/home/gbusey/file.js:6:11)\n // at makeFaster (/home/gbusey/file.js:5:3)\n // at Object.<anonymous> (/home/gbusey/file.js:10:1)\n // at Module._compile (module.js:456:26)\n // at Object.Module._extensions..js (module.js:474:10)\n // at Module.load (module.js:356:32)\n // at Function.Module._load (module.js:312:12)\n // at Function.Module.runMain (module.js:497:10)\n // at startup (node.js:119:16)\n // at node.js:906:3\n
\nThe location information will be one of:
\nnative
, if the frame represents a call internal to V8 (as in [].forEach
).plain-filename.js:line:column
, if the frame represents a call internal\n to Node.js./absolute/path/to/file.js:line:column
, if the frame represents a call in\na user program, or its dependencies.The string representing the stack trace is lazily generated when the\nerror.stack
property is accessed.
The number of frames captured by the stack trace is bounded by the smaller of\nError.stackTraceLimit
or the number of available frames on the current event\nloop tick.
System-level errors are generated as augmented Error
instances, which are\ndetailed here.
Creates a new Error
object and sets the error.message
property to the\nprovided text message. If an object is passed as message
, the text message\nis generated by calling message.toString()
. The error.stack
property will\nrepresent the point in the code at which new Error()
was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit
, whichever is smaller.
Creates a new Error
object and sets the error.message
property to the\nprovided text message. If an object is passed as message
, the text message\nis generated by calling message.toString()
. The error.stack
property will\nrepresent the point in the code at which new Error()
was called. Stack traces\nare dependent on V8's stack trace API. Stack traces extend only to either\n(a) the beginning of synchronous code execution, or (b) the number of frames\ngiven by the property Error.stackTraceLimit
, whichever is smaller.
A subclass of Error
that indicates that a provided argument was not within the\nset or range of acceptable values for a function; whether that is a numeric\nrange, or outside the set of options for a given function parameter.
For example:
\nrequire('net').connect(-1);\n // throws "RangeError: "port" option should be >= 0 and < 65536: -1"\n
\nNode.js will generate and throw RangeError
instances immediately as a form\nof argument validation.
A subclass of Error
that indicates that an attempt is being made to access a\nvariable that is not defined. Such errors commonly indicate typos in code, or\nan otherwise broken program.
While client code may generate and propagate these errors, in practice, only V8\nwill do so.
\ndoesNotExist;\n // throws ReferenceError, doesNotExist is not a variable in this program.\n
\nUnless an application is dynamically generating and running code,\nReferenceError
instances should always be considered a bug in the code\nor its dependencies.
A subclass of Error
that indicates that a program is not valid JavaScript.\nThese errors may only be generated and propagated as a result of code\nevaluation. Code evaluation may happen as a result of eval
, Function
,\nrequire
, or vm. These errors are almost always indicative of a broken\nprogram.
try {\n require('vm').runInThisContext('binary ! isNotOk');\n} catch (err) {\n // err will be a SyntaxError\n}\n
\nSyntaxError
instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.
A subclass of Error
that indicates that a provided argument is not an\nallowable type. For example, passing a function to a parameter which expects a\nstring would be considered a TypeError.
require('url').parse(() => { });\n // throws TypeError, since it expected a string\n
\nNode.js will generate and throw TypeError
instances immediately as a form\nof argument validation.