{ "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.

\n

All errors generated by Node.js, including all System and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

\n", "methods": [ { "textRaw": "Error.captureStackTrace(targetObject[, constructorOpt])", "type": "method", "name": "captureStackTrace", "signatures": [ { "params": [ { "textRaw": "`targetObject` {Object} ", "name": "targetObject", "type": "Object" }, { "textRaw": "`constructorOpt` {Function} ", "name": "constructorOpt", "type": "Function", "optional": true } ] }, { "params": [ { "name": "targetObject" }, { "name": "constructorOpt", "optional": true } ] } ], "desc": "

Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

\n
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack  // similar to `new Error().stack`\n
\n

The first line of the trace, instead of being prefixed with ErrorType:\nmessage, will be the result of calling targetObject.toString().

\n

The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

\n

The constructorOpt argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:

\n
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)).

\n

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.

\n

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).

\n
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.

\n

For example:

\n
Error: 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
\n

The 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.

\n

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:

\n
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
\n

The location information will be one of:

\n\n

The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

\n

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.

\n

System-level errors are generated as augmented Error instances, which are\ndetailed here.

\n" } ] } ], "signatures": [ { "params": [ { "textRaw": "`message` {String} ", "name": "message", "type": "String" } ], "desc": "

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.

\n" }, { "params": [ { "name": "message" } ], "desc": "

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.

\n" } ] }, { "textRaw": "Class: RangeError", "type": "class", "name": "RangeError", "desc": "

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.

\n

For example:

\n
require('net').connect(-1);\n  // throws RangeError, port should be > 0 && < 65536\n
\n

Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

\n" }, { "textRaw": "Class: ReferenceError", "type": "class", "name": "ReferenceError", "desc": "

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.

\n

While client code may generate and propagate these errors, in practice, only V8\nwill do so.

\n
doesNotExist;\n  // throws ReferenceError, doesNotExist is not a variable in this program.\n
\n

ReferenceError 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.

\n
const assert = require('assert');\ntry {\n  doesNotExist;\n} catch(err) {\n  assert(err.arguments[0], 'doesNotExist');\n}\n
\n

Unless an application is dynamically generating and running code,\nReferenceError instances should always be considered a bug in the code\nor its dependencies.

\n" }, { "textRaw": "Class: SyntaxError", "type": "class", "name": "SyntaxError", "desc": "

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.

\n
try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch(err) {\n  // err will be a SyntaxError\n}\n
\n

SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

\n" }, { "textRaw": "Class: TypeError", "type": "class", "name": "TypeError", "desc": "

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.

\n
require('url').parse(() => { });\n  // throws TypeError, since it expected a string\n
\n

Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

\n" } ], "miscs": [ { "textRaw": "Errors", "name": "Errors", "type": "misc", "desc": "

Applications running in Node.js will generally experience four categories of\nerrors:

\n\n

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.

\n

All 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.

\n
// 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
\n

Any 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.

\n

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.

\n

Errors that occur within Asynchronous APIs may be reported in multiple ways:

\n\n

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).

\n

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.

\n
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
\n

Errors generated in this way cannot be intercepted using try / catch as\nthey are thrown after the calling code has already exited.

\n

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.

\n
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
\n

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

\n
// 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
\n

This 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.

\n" } ] }, { "textRaw": "Exceptions vs. Errors", "name": "Exceptions vs. Errors", "type": "misc", "desc": "

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.

\n

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.

\n" }, { "textRaw": "System Errors", "name": "system_errors", "desc": "

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.

\n

System 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.

\n

In Node.js, system errors are represented as augmented Error objects with\nadded properties.

\n", "classes": [ { "textRaw": "Class: System Error", "type": "class", "name": "System", "properties": [ { "textRaw": "`code` {String} ", "type": "String", "name": "code", "desc": "

The error.code property is a string representing the error code, which is always\nE followed by a sequence of capital letters.

\n" }, { "textRaw": "`errno` {String | Number} ", "type": "String | Number", "name": "errno", "desc": "

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.

\n" }, { "textRaw": "`syscall` {String} ", "type": "String", "name": "syscall", "desc": "

The error.syscall property is a string describing the syscall that failed.

\n" }, { "textRaw": "`path` {String} ", "type": "String", "name": "path", "desc": "

When present (e.g. in fs or child_process), the error.path property is a string\ncontaining a relevant invalid pathname.

\n" }, { "textRaw": "`address` {String} ", "type": "String", "name": "address", "desc": "

When present (e.g. in net or dgram), the error.address property is a string\ndescribing the address to which the connection failed.

\n" }, { "textRaw": "`port` {Number} ", "type": "Number", "name": "port", "desc": "

When present (e.g. in net or dgram), the error.port property is a number representing\nthe connection's port that is not available.

\n" } ] } ], "modules": [ { "textRaw": "Common System Errors", "name": "common_system_errors", "desc": "

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.

\n\n", "type": "module", "displayName": "Common System Errors" } ], "type": "misc", "displayName": "System Errors" } ], "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.

\n

All errors generated by Node.js, including all System and JavaScript errors,\nwill either be instances of, or inherit from, the Error class.

\n", "methods": [ { "textRaw": "Error.captureStackTrace(targetObject[, constructorOpt])", "type": "method", "name": "captureStackTrace", "signatures": [ { "params": [ { "textRaw": "`targetObject` {Object} ", "name": "targetObject", "type": "Object" }, { "textRaw": "`constructorOpt` {Function} ", "name": "constructorOpt", "type": "Function", "optional": true } ] }, { "params": [ { "name": "targetObject" }, { "name": "constructorOpt", "optional": true } ] } ], "desc": "

Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace() was called.

\n
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack  // similar to `new Error().stack`\n
\n

The first line of the trace, instead of being prefixed with ErrorType:\nmessage, will be the result of calling targetObject.toString().

\n

The optional constructorOpt argument accepts a function. If given, all frames\nabove constructorOpt, including constructorOpt, will be omitted from the\ngenerated stack trace.

\n

The constructorOpt argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:

\n
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)).

\n

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.

\n

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).

\n
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.

\n

For example:

\n
Error: 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
\n

The 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.

\n

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:

\n
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
\n

The location information will be one of:

\n\n

The string representing the stack trace is lazily generated when the\nerror.stack property is accessed.

\n

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.

\n

System-level errors are generated as augmented Error instances, which are\ndetailed here.

\n" } ] } ], "signatures": [ { "params": [ { "textRaw": "`message` {String} ", "name": "message", "type": "String" } ], "desc": "

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.

\n" }, { "params": [ { "name": "message" } ], "desc": "

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.

\n" } ] }, { "textRaw": "Class: RangeError", "type": "class", "name": "RangeError", "desc": "

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.

\n

For example:

\n
require('net').connect(-1);\n  // throws RangeError, port should be > 0 && < 65536\n
\n

Node.js will generate and throw RangeError instances immediately as a form\nof argument validation.

\n" }, { "textRaw": "Class: ReferenceError", "type": "class", "name": "ReferenceError", "desc": "

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.

\n

While client code may generate and propagate these errors, in practice, only V8\nwill do so.

\n
doesNotExist;\n  // throws ReferenceError, doesNotExist is not a variable in this program.\n
\n

ReferenceError 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.

\n
const assert = require('assert');\ntry {\n  doesNotExist;\n} catch(err) {\n  assert(err.arguments[0], 'doesNotExist');\n}\n
\n

Unless an application is dynamically generating and running code,\nReferenceError instances should always be considered a bug in the code\nor its dependencies.

\n" }, { "textRaw": "Class: SyntaxError", "type": "class", "name": "SyntaxError", "desc": "

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.

\n
try {\n  require('vm').runInThisContext('binary ! isNotOk');\n} catch(err) {\n  // err will be a SyntaxError\n}\n
\n

SyntaxError instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.

\n" }, { "textRaw": "Class: TypeError", "type": "class", "name": "TypeError", "desc": "

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.

\n
require('url').parse(() => { });\n  // throws TypeError, since it expected a string\n
\n

Node.js will generate and throw TypeError instances immediately as a form\nof argument validation.

\n" } ] } ] }