{
  "source": "doc/api/errors.markdown",
  "miscs": [
    {
      "textRaw": "Errors",
      "name": "Errors",
      "type": "misc",
      "desc": "<p>Errors generated by Node.js fall into two categories: JavaScript errors and system\nerrors. All errors inherit from or are instances of JavaScript&#39;s [Error][]\nclass and are guaranteed to provide <em>at least</em> the attributes available on that\nclass.\n\n</p>\n<p>When an operation is not permitted due to language-syntax or\nlanguage-runtime-level reasons, a <strong>JavaScript error</strong> is generated and thrown\nas an <strong>exception</strong>. If an operation is not allowed due to system-level\nrestrictions, a <strong>system error</strong> is generated. Client code is then given the\nopportunity to <strong>intercept</strong> this error based on how the API <strong>propagates</strong> it.\n\n</p>\n<p>The style of API called determines how generated errors are handed back, or\n<strong>propagated</strong>, to client code, which in turn informs how the client may <strong>intercept</strong>\nthe error. Exceptions can be intercepted using the <code>try / catch</code> construct;\nother propagation strategies are covered [below][].\n\n</p>\n",
      "miscs": [
        {
          "textRaw": "Error Propagation and Interception",
          "name": "Error Propagation and Interception",
          "type": "misc",
          "desc": "<p>All Node.js APIs will treat invalid arguments as exceptional -- that is, if passed\ninvalid arguments, they will <em>immediately</em> generate and throw the error as an\nexception, even if they are an otherwise asynchronous API.\n\n</p>\n<p>Synchronous APIs (like [fs.readFileSync][]) will throw the error. The act of\n<em>throwing</em> a value (in this case, the error) turns the value into an <strong>exception</strong>.\nExceptions may be caught using the <code>try { } catch(err) { }</code> construct.\n\n</p>\n<p>Asynchronous APIs have <strong>two</strong> 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</p>\n",
          "miscs": [
            {
              "textRaw": "Error events",
              "name": "Error events",
              "type": "misc",
              "desc": "<p>The other mechanism for providing errors is the &quot;error&quot; 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 &quot;error&quot; 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(&#39;uncaughtException&#39;)][] has a handler.\n\n</p>\n<pre><code class=\"javascript\">var net = require(&#39;net&#39;);\n\nvar connection = net.connect(&#39;localhost&#39;);\n\n// adding an &quot;error&quot; event handler to a stream:\nconnection.on(&#39;error&#39;, function(err) {\n  // if the connection is reset by the server, or if it can&#39;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);</code></pre>\n<p>The &quot;throw when no error handlers are attached behavior&quot; 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</p>\n<pre><code class=\"javascript\">var EventEmitter = require(&#39;events&#39;);\n\nvar ee = new EventEmitter();\n\nsetImmediate(function() {\n  // this will crash the process because no &quot;error&quot; event\n  // handler has been added.\n  ee.emit(&#39;error&#39;, new Error(&#39;This will crash&#39;));\n});</code></pre>\n<p>As with node style callbacks, errors generated this way <em>cannot</em> be intercepted\nby <code>try { } catch(err) { }</code> -- they happen <em>after</em> the calling code has already\nexited.\n\n</p>\n"
            },
            {
              "textRaw": "Node style callbacks",
              "name": "Node style callbacks",
              "type": "misc",
              "desc": "<p>Single operation APIs take &quot;node style callbacks&quot; -- a\nfunction provided to the API as an argument. The node style callback takes\nat least <strong>one</strong> argument -- <code>error</code> -- that will either be <code>null</code> (if no error\nwas encountered) or an <code>Error</code> instance.  For instance:\n\n</p>\n<pre><code class=\"javascript\">var fs = require(&#39;fs&#39;);\n\nfs.readFile(&#39;/some/file/that/does-not-exist&#39;, function nodeStyleCallback(err, data) {\n  console.log(err)  // Error: ENOENT\n  console.log(data) // undefined / null\n});\n\nfs.readFile(&#39;/some/file/that/does-exist&#39;, function(err, data) {\n  console.log(err)  // null\n  console.log(data) // &lt;Buffer: ba dd ca fe&gt;\n})</code></pre>\n<p>Note that <code>try { } catch(err) { }</code> <strong>cannot</strong> intercept errors generated by\nasynchronous APIs. A common mistake for beginners is to try to use <code>throw</code>\ninside their node style callback:\n\n</p>\n<pre><code class=\"javascript\">// THIS WILL NOT WORK:\nvar fs = require(&#39;fs&#39;);\n\ntry {\n  fs.readFile(&#39;/some/file/that/does-not-exist&#39;, 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}</code></pre>\n<p>This will not work! By the time the node style callback has been called, the\nsurrounding code (including the <code>try { } catch(err) { }</code> will have already\nexited. Throwing an error inside a node style callback <strong>will crash the process</strong> in most cases.\nIf [domains][] are enabled, they may intercept the thrown error; similarly, if a\nhandler has been added to <code>process.on(&#39;uncaughtException&#39;)</code>, it will intercept\nthe error.\n\n</p>\n"
            }
          ]
        },
        {
          "textRaw": "JavaScript Errors",
          "name": "JavaScript Errors",
          "type": "misc",
          "desc": "<p>JavaScript errors typically denote that an API is being used incorrectly, or that\nthere is a problem with the program as written.\n\n</p>\n",
          "classes": [
            {
              "textRaw": "Class: Error",
              "type": "class",
              "name": "Error",
              "desc": "<p>A general error object. Unlike other error objects, <code>Error</code> instances do not\ndenote any specific circumstance of why the error occurred. Errors capture a\n&quot;stack trace&quot; detailing the point in the program at which they were\ninstantiated, and may provide a description of the error.\n\n</p>\n<p><strong>Note</strong>: Node.js will generate this class of error to encapsulate system\nerrors as well as plain JavaScript errors.\n\n</p>\n",
              "methods": [
                {
                  "textRaw": "Error.captureStackTrace(targetObject[, constructorOpt])",
                  "type": "method",
                  "name": "captureStackTrace",
                  "desc": "<p>Creates a <code>.stack</code> property on <code>targetObject</code>, which when accessed returns\na string representing the location in the program at which <code>Error.captureStackTrace</code>\nwas called.\n\n</p>\n<pre><code class=\"javascript\">var myObject = {};\n\nError.captureStackTrace(myObject);\n\nmyObject.stack  // similar to `new Error().stack`</code></pre>\n<p>The first line of the trace, instead of being prefixed with <code>ErrorType:\nmessage</code>, will be the result of <code>targetObject.toString()</code>.\n\n</p>\n<p><code>constructorOpt</code> optionally accepts a function. If given, all frames above\n<code>constructorOpt</code>, including <code>constructorOpt</code>, will be omitted from the generated\nstack trace.\n\n</p>\n<p>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</p>\n<pre><code class=\"javascript\">\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</code></pre>\n",
                  "signatures": [
                    {
                      "params": [
                        {
                          "name": "targetObject"
                        },
                        {
                          "name": "constructorOpt",
                          "optional": true
                        }
                      ]
                    }
                  ]
                }
              ],
              "properties": [
                {
                  "textRaw": "Error.stackTraceLimit",
                  "name": "stackTraceLimit",
                  "desc": "<p>Property that determines the number of stack frames collected by a stack trace\n(whether generated by <code>new Error().stack</code> or <code>Error.captureStackTrace(obj)</code>).\n\n</p>\n<p>The initial value is <code>10</code>. It may be set to any valid JavaScript number, which\nwill affect any stack trace captured <em>after</em> the value has been changed. If set\nto a non-number value, stack traces will not capture any frames and will report\n<code>undefined</code> on access.\n\n</p>\n"
                },
                {
                  "textRaw": "error.message",
                  "name": "message",
                  "desc": "<p>A string of the value passed to <code>Error()</code> upon instantiation. The message will\nalso appear in the first line of the stack trace of the error. Changing this\nproperty <em>may not</em> change the first line of the stack trace.\n\n</p>\n"
                },
                {
                  "textRaw": "error.stack",
                  "name": "stack",
                  "desc": "<p>A property that, when <strong>accessed</strong>, returns a string representing the point in the program\nat which this error was instantiated. An example stacktrace follows:\n\n</p>\n<pre><code>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.&lt;anonymous&gt; (/home/gbusey/actors.js:400:8)\n   at increaseSynergy (/home/gbusey/actors.js:701:6)</code></pre>\n<p>The first line is formatted as <code>&lt;error class name&gt;: &lt;error message&gt;</code>, and it is followed\nby a series of stack frames (each line beginning with &quot;at &quot;). 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</p>\n<p>Frames are <strong>only</strong> generated for JavaScript functions. If, for example, execution\nsynchronously passes through a C++ addon function called <code>cheetahify</code>, which itself\ncalls a JavaScript function, the frame representing the <code>cheetahify</code> call will <strong>not</strong>\nbe present in stacktraces:\n\n</p>\n<pre><code class=\"javascript\">var cheetahify = require(&#39;./native-binding.node&#39;);\n\nfunction makeFaster() {\n  // cheetahify *synchronously* calls speedy.\n  cheetahify(function speedy() {\n    throw new Error(&#39;oh no!&#39;);\n  });\n}\n\nmakeFaster(); // will throw:\n// /home/gbusey/file.js:6\n//     throw new Error(&#39;oh no!&#39;);\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.&lt;anonymous&gt; (/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</code></pre>\n<p>The location information will be one of:\n\n</p>\n<ul>\n<li><code>native</code>, if the frame represents a call internal to V8 (as in <code>[].forEach</code>).</li>\n<li><code>plain-filename.js:line:column</code>, if the frame represents a call internal to Node.js.</li>\n<li><code>/absolute/path/to/file.js:line:column</code>, if the frame represents a call in a user program, or its dependencies.</li>\n</ul>\n<p>It is important to note that the string representing the stacktrace is only\ngenerated on <strong>access</strong>: it is lazily generated.\n\n</p>\n<p>The number of frames captured by the stack trace is bounded by the smaller of\n<code>Error.stackTraceLimit</code> or the number of available frames on the current event\nloop tick.\n\n</p>\n<p>System-level errors are generated as augmented Error instances, which are detailed\n<a href=\"#errors_system_errors\">below</a>.\n\n</p>\n"
                }
              ],
              "signatures": [
                {
                  "params": [
                    {
                      "name": "message"
                    }
                  ],
                  "desc": "<p>Instantiates a new Error object and sets its <code>.message</code> property to the provided\nmessage. Its <code>.stack</code> will represent the point in the program at which <code>new Error</code>\nwas called. Stack traces are subject to [V8&#39;s stack trace API][].\nStack traces only extend to the beginning of synchronous code execution, <em>or</em> a number of frames given by\n<code>Error.stackTraceLimit</code>, whichever is smaller.\n\n</p>\n"
                }
              ]
            },
            {
              "textRaw": "Class: RangeError",
              "type": "class",
              "name": "RangeError",
              "desc": "<p>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</p>\n<pre><code class=\"javascript\">require(&#39;net&#39;).connect(-1);  // throws RangeError, port should be &gt; 0 &amp;&amp; &lt; 65536</code></pre>\n<p>Node.js will generate and throw RangeError instances <em>immediately</em> -- they are a form\nof argument validation.\n\n</p>\n"
            },
            {
              "textRaw": "Class: ReferenceError",
              "type": "class",
              "name": "ReferenceError",
              "desc": "<p>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</p>\n<pre><code class=\"javascript\">doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program.</code></pre>\n<p>ReferenceError instances will have an <code>.arguments</code> member that is an array containing\none element -- a string representing the variable that was not defined.\n\n</p>\n<pre><code class=\"javascript\">try {\n  doesNotExist;\n} catch(err) {\n  err.arguments[0] === &#39;doesNotExist&#39;;\n}</code></pre>\n<p>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</p>\n"
            },
            {
              "textRaw": "Class: SyntaxError",
              "type": "class",
              "name": "SyntaxError",
              "desc": "<p>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 <code>eval</code>, <code>Function</code>,\n<code>require</code>, or [vm][]. These errors are almost always indicative of a broken\nprogram.\n\n</p>\n<pre><code class=\"javascript\">try {\n  require(&quot;vm&quot;).runInThisContext(&quot;binary ! isNotOk&quot;);\n} catch(err) {\n  // err will be a SyntaxError\n}</code></pre>\n<p>SyntaxErrors are unrecoverable from the context that created them – they may only be caught\nby other contexts.\n\n</p>\n"
            },
            {
              "textRaw": "Class: TypeError",
              "type": "class",
              "name": "TypeError",
              "desc": "<p>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</p>\n<pre><code class=\"javascript\">require(&#39;url&#39;).parse(function() { }); // throws TypeError, since it expected a string</code></pre>\n<p>Node.js will generate and throw TypeError instances <em>immediately</em> -- they are a form\nof argument validation.\n\n</p>\n"
            }
          ],
          "miscs": [
            {
              "textRaw": "Exceptions vs. Errors",
              "name": "Exceptions vs. Errors",
              "type": "misc",
              "desc": "<p>A JavaScript &quot;exception&quot; is a value that is thrown as a result of an invalid operation or\nas the target of a <code>throw</code> statement. While it is not required that these values inherit from\n<code>Error</code>, all exceptions thrown by Node.js or the JavaScript runtime <em>will</em> be instances of Error.\n\n</p>\n<p>Some exceptions are <em>unrecoverable</em> at the JavaScript layer. These exceptions will always bring\ndown the process. These are usually failed <code>assert()</code> checks or <code>abort()</code> calls in the C++ layer.\n\n</p>\n"
            }
          ]
        },
        {
          "textRaw": "System Errors",
          "name": "system_errors",
          "desc": "<p>System errors are generated in response to a program&#39;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 <code>man 2 intro</code> or <code>man 3 errno</code>\non most Unices; or [online][].\n\n</p>\n<p>In Node.js, system errors are represented as augmented Error objects -- not full\nsubclasses, but instead an error instance with added members.\n\n</p>\n",
          "classes": [
            {
              "textRaw": "Class: System Error",
              "type": "class",
              "name": "System",
              "properties": [
                {
                  "textRaw": "error.code",
                  "name": "code",
                  "desc": "<p>A string representing the error code, which is always <code>E</code> followed by capital\nletters, and may be referenced in <code>man 2 intro</code>.\n\n</p>\n"
                },
                {
                  "textRaw": "error.errno",
                  "name": "errno",
                  "desc": "<p>A string representing the error code, which is always <code>E</code> followed by capital\nletters, and may be referenced in <code>man 2 intro</code>.\n\n</p>\n"
                },
                {
                  "textRaw": "error.syscall",
                  "name": "syscall",
                  "desc": "<p>A string representing the [syscall][] that failed.\n\n</p>\n"
                }
              ]
            }
          ],
          "modules": [
            {
              "textRaw": "Common System Errors",
              "name": "common_system_errors",
              "desc": "<p>This list is <strong>not exhaustive</strong>, but enumerates many of the common system errors when\nwriting a Node.js program. An exhaustive list may be found [here][online].\n\n</p>\n",
              "modules": [
                {
                  "textRaw": "EACCES: Permission denied",
                  "name": "eacces:_permission_denied",
                  "desc": "<p>An attempt was made to access a file in a way forbidden by its file access\npermissions.\n\n</p>\n",
                  "type": "module",
                  "displayName": "EACCES: Permission denied"
                },
                {
                  "textRaw": "EADDRINUSE: Address already in use",
                  "name": "eaddrinuse:_address_already_in_use",
                  "desc": "<p>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</p>\n",
                  "type": "module",
                  "displayName": "EADDRINUSE: Address already in use"
                },
                {
                  "textRaw": "ECONNREFUSED: Connection refused",
                  "name": "econnrefused:_connection_refused",
                  "desc": "<p>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</p>\n",
                  "type": "module",
                  "displayName": "ECONNREFUSED: Connection refused"
                },
                {
                  "textRaw": "ECONNRESET: Connection reset by peer",
                  "name": "econnreset:_connection_reset_by_peer",
                  "desc": "<p>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</p>\n",
                  "type": "module",
                  "displayName": "ECONNRESET: Connection reset by peer"
                },
                {
                  "textRaw": "EEXIST: File exists",
                  "name": "eexist:_file_exists",
                  "desc": "<p>An existing file was the target of an operation that required that the target\nnot exist.\n\n</p>\n",
                  "type": "module",
                  "displayName": "EEXIST: File exists"
                },
                {
                  "textRaw": "EISDIR: Is a directory",
                  "name": "eisdir:_is_a_directory",
                  "desc": "<p>An operation expected a file, but the given pathname was a directory.\n\n</p>\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": "<p>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</p>\n<p>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 <code>ulimit -n 2048</code> in the same shell\nthat will run the Node.js process.\n\n</p>\n",
                  "type": "module",
                  "displayName": "EMFILE: Too many open files in system"
                },
                {
                  "textRaw": "ENOENT: No such file or directory",
                  "name": "enoent:_no_such_file_or_directory",
                  "desc": "<p>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</p>\n",
                  "type": "module",
                  "displayName": "ENOENT: No such file or directory"
                },
                {
                  "textRaw": "ENOTDIR: Not a directory",
                  "name": "enotdir:_not_a_directory",
                  "desc": "<p>A component of the given pathname existed, but was not a directory as expected.\nCommonly raised by [fs.readdir][].\n\n</p>\n",
                  "type": "module",
                  "displayName": "ENOTDIR: Not a directory"
                },
                {
                  "textRaw": "ENOTEMPTY: Directory not empty",
                  "name": "enotempty:_directory_not_empty",
                  "desc": "<p>A directory with entries was the target of an operation that requires\nan empty directory -- usually [fs.unlink][].\n\n</p>\n",
                  "type": "module",
                  "displayName": "ENOTEMPTY: Directory not empty"
                },
                {
                  "textRaw": "EPERM: Operation not permitted",
                  "name": "eperm:_operation_not_permitted",
                  "desc": "<p>An attempt was made to perform an operation that requires appropriate\nprivileges.\n\n</p>\n",
                  "type": "module",
                  "displayName": "EPERM: Operation not permitted"
                },
                {
                  "textRaw": "EPIPE: Broken pipe",
                  "name": "epipe:_broken_pipe",
                  "desc": "<p>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</p>\n",
                  "type": "module",
                  "displayName": "EPIPE: Broken pipe"
                },
                {
                  "textRaw": "ETIMEDOUT: Operation timed out",
                  "name": "etimedout:_operation_timed_out",
                  "desc": "<p>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 <code>.end()</code>&#39;d appropriately.\n\n</p>\n",
                  "type": "module",
                  "displayName": "ETIMEDOUT: Operation timed out"
                }
              ],
              "type": "module",
              "displayName": "Common System Errors"
            }
          ],
          "type": "misc",
          "displayName": "System Errors"
        }
      ]
    }
  ]
}
