{ "source": "doc/api/errors.markdown", "miscs": [ { "textRaw": "Errors", "name": "Errors", "type": "misc", "desc": "

Errors generated by Node.js fall into two categories: JavaScript errors and system\nerrors. All errors inherit from or are instances of JavaScript's Error\nclass and are guaranteed to provide at least the attributes available on that\nclass.\n\n

\n

When an operation is not permitted due to language-syntax or\nlanguage-runtime-level reasons, a JavaScript error is generated and thrown\nas an exception. If an operation is not allowed due to system-level\nrestrictions, a system error is generated. Client code is then given the\nopportunity to intercept this error based on how the API propagates it.\n\n

\n

The style of API called determines how generated errors are handed back, or\npropagated, to client code, which in turn informs how the client may intercept\nthe error. Exceptions can be intercepted using the try / catch construct;\nother propagation strategies are covered below.\n\n

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

JavaScript errors typically denote that an API is being used incorrectly, or that\nthere is a problem with the program as written.\n\n

\n", "classes": [ { "textRaw": "Class: Error", "type": "class", "name": "Error", "desc": "

A general error object. Unlike other error objects, Error instances do not\ndenote any specific circumstance of why the error occurred. Errors capture a\n"stack trace" detailing the point in the program at which they were\ninstantiated, and may provide a description of the error.\n\n

\n

Note: Node.js will generate this class of error to encapsulate system\nerrors as well as plain JavaScript errors.\n\n

\n", "properties": [ { "textRaw": "error.message", "name": "message", "desc": "

A string of the value passed to Error() upon instantiation. The message will\nalso appear in the first line of the stack trace of the error. Changing this\nproperty may not change the first line of the stack trace.\n\n

\n" }, { "textRaw": "error.stack", "name": "stack", "desc": "

A property that, when accessed, returns a string representing the point in the program\nat which this error was instantiated. An example stacktrace follows:\n\n

\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

The first line is formatted as <error class name>: <error message>, and it is followed\nby a series of stack frames (each line beginning with "at "). Each frame describes\na call site in the program that lead to the error being generated. V8 attempts to\ndisplay a name for each function (by variable name, function name, or object\nmethod name), but occasionally it will not be able to find a suitable name. If\nV8 cannot determine a name for the function, only location information will be\ndisplayed for that frame. Otherwise, the determined function name will be displayed\nwith location information appended in parentheses.\n\n

\n

Frames are only generated for JavaScript functions. If, for example, execution\nsynchronously passes through a C++ addon function called cheetahify, which itself\ncalls a JavaScript function, the frame representing the cheetahify call will not\nbe present in stacktraces:\n\n

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

The location information will be one of:\n\n

\n\n

It is important to note that the string representing the stacktrace is only\ngenerated on access: it is lazily generated.\n\n

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

\n

System-level errors are generated as augmented Error instances, which are detailed\nbelow.\n\n

\n" }, { "textRaw": "Error.stackTraceLimit", "name": "stackTraceLimit", "desc": "

Property that determines the number of stack frames collected by a stack trace\n(whether generated by new Error().stack or Error.captureStackTrace(obj)).\n\n

\n

The initial value is 10. It may be set to any valid JavaScript number, which\nwill affect any stack trace captured after the value has been changed. If set\nto a non-number value, stack traces will not capture any frames and will report\nundefined on access.\n\n

\n" } ], "methods": [ { "textRaw": "Error.captureStackTrace(targetObject[, constructorOpt])", "type": "method", "name": "captureStackTrace", "desc": "

Creates a .stack property on targetObject, which when accessed returns\na string representing the location in the program at which Error.captureStackTrace\nwas called.\n\n

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

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

\n

constructorOpt optionally accepts a function. If given, all frames above\nconstructorOpt, including constructorOpt, will be omitted from the generated\nstack trace.\n\n

\n

This is useful for hiding implementation details of error generation from the\nend user. A common way of using this parameter is to pass the current Error\nconstructor to it:\n\n

\n
\nfunction MyError() {\n  Error.captureStackTrace(this, MyError);\n}\n\n// without passing MyError to captureStackTrace, the MyError\n// frame would should up in the .stack property. by passing\n// the constructor, we omit that frame and all frames above it.\nnew MyError().stack
\n", "signatures": [ { "params": [ { "name": "targetObject" }, { "name": "constructorOpt", "optional": true } ] } ] } ], "signatures": [ { "params": [ { "name": "message" } ], "desc": "

Instantiates a new Error object and sets its .message property to the provided\nmessage. Its .stack will represent the point in the program at which new Error\nwas called. Stack traces are subject to V8's stack trace API.\nStack traces only extend to the beginning of synchronous code execution, or a number of frames given by\nError.stackTraceLimit, whichever is smaller.\n\n

\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 be a numeric\nrange, or outside the set of options for a given function parameter. An example:\n\n

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

Node.js will generate and throw RangeError instances immediately -- they are a form\nof argument validation.\n\n

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

A subclass of Error that indicates that a provided argument is not an allowable\ntype. For example, passing a function to a parameter which expects a string would\nbe considered a TypeError.\n\n

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

Node.js will generate and throw TypeError instances immediately -- they are a form\nof argument validation.\n\n

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

A subclass of Error that indicates that an attempt is being made to access a variable\nthat is not defined. Most commonly it indicates a typo, or an otherwise broken program.\nWhile client code may generate and propagate these errors, in practice only V8 will do\nso.\n\n

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

ReferenceError instances will have an .arguments member that is an array containing\none element -- a string representing the variable that was not defined.\n\n

\n
try {\n  doesNotExist;\n} catch(err) {\n  err.arguments[0] === 'doesNotExist';\n}
\n

Unless the userland program is dynamically generating and running code,\nReferenceErrors should always be considered a bug in the program, or its\ndependencies.\n\n

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

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

SyntaxErrors are unrecoverable from the context that created them – they may only be caught\nby other contexts.\n\n

\n" } ], "miscs": [ { "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 operation or\nas the target of a throw statement. While it is not required that these values inherit from\nError, all exceptions thrown by Node.js or the JavaScript runtime will be instances of Error.\n\n

\n

Some exceptions are unrecoverable at the JavaScript layer. These exceptions will always bring\ndown the process. These are usually failed assert() checks or abort() calls in the C++ layer.\n\n

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

System errors are generated in response to a program's runtime environment.\nIdeally, they represent operational errors that the program needs to be able to\nreact to. They are generated at the syscall level: an exhaustive list of error\ncodes and their meanings is available by running man 2 intro or man 3 errno\non most Unices; or online.\n\n

\n

In Node.js, system errors are represented as augmented Error objects -- not full\nsubclasses, but instead an error instance with added members.\n\n

\n", "classes": [ { "textRaw": "Class: System Error", "type": "class", "name": "System", "properties": [ { "textRaw": "error.syscall", "name": "syscall", "desc": "

A string representing the syscall that failed.\n\n

\n" }, { "textRaw": "error.errno", "name": "errno", "desc": "

A string representing the error code, which is always E followed by capital\nletters, and may be referenced in man 2 intro.\n\n

\n" }, { "textRaw": "error.code", "name": "code", "desc": "

A string representing the error code, which is always E followed by capital\nletters, and may be referenced in man 2 intro.\n\n

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

This list is not exhaustive, but enumerates many of the common system errors when\nwriting a Node.js program. An exhaustive list may be found here.\n\n

\n", "modules": [ { "textRaw": "EPERM: Operation not permitted", "name": "eperm:_operation_not_permitted", "desc": "

An attempt was made to perform an operation that requires appropriate\nprivileges.\n\n

\n", "type": "module", "displayName": "EPERM: Operation not permitted" }, { "textRaw": "ENOENT: No such file or directory", "name": "enoent:_no_such_file_or_directory", "desc": "

Commonly raised by fs operations; a component of the specified pathname\ndoes not exist -- no entity (file or directory) could be found by the given path.\n\n

\n", "type": "module", "displayName": "ENOENT: No such file or directory" }, { "textRaw": "EACCES: Permission denied", "name": "eacces:_permission_denied", "desc": "

An attempt was made to access a file in a way forbidden by its file access\npermissions.\n\n

\n", "type": "module", "displayName": "EACCES: Permission denied" }, { "textRaw": "EEXIST: File exists", "name": "eexist:_file_exists", "desc": "

An existing file was the target of an operation that required that the target\nnot exist.\n\n

\n", "type": "module", "displayName": "EEXIST: File exists" }, { "textRaw": "ENOTDIR: Not a directory", "name": "enotdir:_not_a_directory", "desc": "

A component of the given pathname existed, but was not a directory as expected.\nCommonly raised by fs.readdir.\n\n

\n", "type": "module", "displayName": "ENOTDIR: Not a directory" }, { "textRaw": "EISDIR: Is a directory", "name": "eisdir:_is_a_directory", "desc": "

An operation expected a file, but the given pathname was a directory.\n\n

\n", "type": "module", "displayName": "EISDIR: Is a directory" }, { "textRaw": "EMFILE: Too many open files in system", "name": "emfile:_too_many_open_files_in_system", "desc": "

Maximum number of file descriptors allowable on the system has\nbeen reached, and requests for another descriptor cannot be fulfilled until\nat least one has been closed.\n\n

\n

Commonly encountered when opening many files at once in parallel, especially\non systems (in particular, OS X) where there is a low file descriptor limit\nfor processes. To remedy a low limit, run ulimit -n 2048 in the same shell\nthat will run the Node.js process.\n\n

\n", "type": "module", "displayName": "EMFILE: Too many open files in system" }, { "textRaw": "EPIPE: Broken pipe", "name": "epipe:_broken_pipe", "desc": "

A write on a pipe, socket, or FIFO for which there is no process to read the\ndata. Commonly encountered at the net and http layers, indicative that\nthe remote side of the stream being written to has been closed.\n\n

\n", "type": "module", "displayName": "EPIPE: Broken pipe" }, { "textRaw": "EADDRINUSE: Address already in use", "name": "eaddrinuse:_address_already_in_use", "desc": "

An attempt to bind a server (net, http, or https) to a local\naddress failed due to another server on the local system already occupying\nthat address.\n\n

\n", "type": "module", "displayName": "EADDRINUSE: Address already in use" }, { "textRaw": "ECONNRESET: Connection reset by peer", "name": "econnreset:_connection_reset_by_peer", "desc": "

A connection was forcibly closed by a peer. This normally results\nfrom a loss of the connection on the remote socket due to a timeout\nor reboot. Commonly encountered via the http and net modules.\n\n

\n", "type": "module", "displayName": "ECONNRESET: Connection reset by peer" }, { "textRaw": "ECONNREFUSED: Connection refused", "name": "econnrefused:_connection_refused", "desc": "

No connection could be made because the target machine actively refused\nit. This usually results from trying to connect to a service that is inactive\non the foreign host.\n\n

\n", "type": "module", "displayName": "ECONNREFUSED: Connection refused" }, { "textRaw": "ENOTEMPTY: Directory not empty", "name": "enotempty:_directory_not_empty", "desc": "

A directory with entries was the target of an operation that requires\nan empty directory -- usually fs.unlink.\n\n

\n", "type": "module", "displayName": "ENOTEMPTY: Directory not empty" }, { "textRaw": "ETIMEDOUT: Operation timed out", "name": "etimedout:_operation_timed_out", "desc": "

A connect or send request failed because the connected party did not properly\nrespond after a period of time. Usually encountered by http or net --\noften a sign that a connected socket was not .end()'d appropriately.\n\n

\n", "type": "module", "displayName": "ETIMEDOUT: Operation timed out" } ], "type": "module", "displayName": "Common System Errors" } ], "type": "misc", "displayName": "System Errors" }, { "textRaw": "Error Propagation and Interception", "name": "Error Propagation and Interception", "type": "misc", "desc": "

All Node.js APIs will treat invalid arguments as exceptional -- that is, if passed\ninvalid arguments, they will immediately generate and throw the error as an\nexception, even if they are an otherwise asynchronous API.\n\n

\n

Synchronous APIs (like\nfs.readFileSync) will throw the\nerror. The act of throwing a value (in this case, the error) turns the value\ninto an exception. Exceptions may be caught using the try { } catch(err)\n{ } construct.\n\n

\n

Asynchronous APIs have two mechanisms for error propagation; one mechanism\nfor APIs that represent a single operation, and one for APIs that represent\nmultiple operations over time.\n\n

\n", "miscs": [ { "textRaw": "Node style callbacks", "name": "Node style callbacks", "type": "misc", "desc": "

Single operation APIs take "node style callbacks" -- a\nfunction provided to the API as an argument. The node style callback takes\nat least one argument -- error -- that will either be null (if no error\nwas encountered) or an Error instance. For instance:\n\n

\n
var fs = require('fs');\n\nfs.readFile('/some/file/that/does-not-exist', function nodeStyleCallback(err, data) {\n  console.log(err)  // Error: ENOENT\n  console.log(data) // undefined / null\n});\n\nfs.readFile('/some/file/that/does-exist', function(err, data) {\n  console.log(err)  // null\n  console.log(data) // <Buffer: ba dd ca fe>\n})
\n

Note that try { } catch(err) { } cannot intercept errors generated by\nasynchronous APIs. A common mistake for beginners is to try to use throw\ninside their node style callback:\n\n

\n
// THIS WILL NOT WORK:\nvar fs = require('fs');\n\ntry {\n  fs.readFile('/some/file/that/does-not-exist', function(err, data) {\n    // mistaken assumption: throwing here...\n    if (err) {\n      throw err;\n    }\n  });\n} catch(err) {\n  // ... will be caught here -- this is incorrect!\n  console.log(err); // Error: ENOENT\n}
\n

This will not work! By the time the node style callback has been called, the\nsurrounding code (including the try { } catch(err) { } will have already\nexited. Throwing an error inside a node style callback will crash the process in most cases.\nIf domains are enabled, they may intercept the thrown error; similarly, if a\nhandler has been added to process.on('uncaughtException'), it will intercept\nthe error.\n\n

\n" }, { "textRaw": "Error events", "name": "Error events", "type": "misc", "desc": "

The other mechanism for providing errors is the "error" event. This is\ntypically used by stream-based and event emitter-based APIs, which\nthemselves represent a series of asynchronous operations over time (versus a\nsingle operation that may pass or fail). If no "error" event handler is\nattached to the source of the error, the error will be thrown. At this point,\nit will crash the process as an unhandled exception unless domains are\nemployed appropriately or process.on('uncaughtException') has a handler.\n\n

\n
var net = require('net');\n\nvar connection = net.connect('localhost');\n\n// adding an "error" event handler to a stream:\nconnection.on('error', function(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

The "throw when no error handlers are attached behavior" is not limited to APIs\nprovided by Node.js -- even user created event emitters and streams will throw\nerrors when no error handlers are attached. An example:\n\n

\n
var EventEmitter = require('events');\n\nvar ee = new EventEmitter();\n\nsetImmediate(function() {\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

As with node style callbacks, errors generated this way cannot be intercepted\nby try { } catch(err) { } -- they happen after the calling code has already\nexited.\n

\n" } ] } ] } ] }