{ "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 all frames above 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": "`message` {String} ", "type": "String", "name": "message", "desc": "The error.message
property is the string description of the error as set by calling new Error(message)
.\nThe message
passed to the constructor will also appear in the first line of\nthe stack trace of the Error
, however changing this property after the\nError
object is created may not change the first line of the stack trace\n(for example, when error.stack
is read before this property is changed).
const err = new Error('The message');\nconsole.log(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 should be > 0 && < 65536\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
\nReferenceError
instances will have an error.arguments
property whose value\nis an array containing a single element: a string representing the variable\nthat was not defined.
const assert = require('assert');\ntry {\n doesNotExist;\n} catch(err) {\n assert(err.arguments[0], 'doesNotExist');\n}\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 JavaScript\nlanguage.
// 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:
\nMost asynchronous methods that accept a callback
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');\nfs.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 used\nappropriately 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.log(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 always\nE
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 in\nlibuv Error handling
. See uv-errno.h header file (deps/uv/include/uv-errno.h
in\nthe Node.js source tree) for details.\nIn case of 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 string\ncontaining a relevant invalid pathname.
When present (e.g. in net
or dgram
), the error.address
property is a string\ndescribing the address to which the connection failed.
When present (e.g. in net
or dgram
), the error.port
property is a number representing\nthe 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, OS X) 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.
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 all frames above 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": "`message` {String} ", "type": "String", "name": "message", "desc": "The error.message
property is the string description of the error as set by calling new Error(message)
.\nThe message
passed to the constructor will also appear in the first line of\nthe stack trace of the Error
, however changing this property after the\nError
object is created may not change the first line of the stack trace\n(for example, when error.stack
is read before this property is changed).
const err = new Error('The message');\nconsole.log(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 should be > 0 && < 65536\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
\nReferenceError
instances will have an error.arguments
property whose value\nis an array containing a single element: a string representing the variable\nthat was not defined.
const assert = require('assert');\ntry {\n doesNotExist;\n} catch(err) {\n assert(err.arguments[0], 'doesNotExist');\n}\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.