5 Errors generated by Node.js fall into two categories: JavaScript errors and system
6 errors. All errors inherit from or are instances of JavaScript's [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
7 class and are guaranteed to provide *at least* the attributes available on that
10 When an operation is not permitted due to language-syntax or
11 language-runtime-level reasons, a **JavaScript error** is generated and thrown
12 as an **exception**. If an operation is not allowed due to system-level
13 restrictions, a **system error** is generated. Client code is then given the
14 opportunity to **intercept** this error based on how the API **propagates** it.
16 The style of API called determines how generated errors are handed back, or
17 **propagated**, to client code, which in turn informs how the client may **intercept**
18 the error. Exceptions can be intercepted using the `try / catch` construct;
19 other propagation strategies are covered [below](#errors_error_propagation_and_interception).
21 ## Error Propagation and Interception
25 All Node.js APIs will treat invalid arguments as exceptional -- that is, if passed
26 invalid arguments, they will *immediately* generate and throw the error as an
27 exception, even if they are an otherwise asynchronous API.
29 Synchronous APIs (like
30 [fs.readFileSync](fs.html#fs_fs_readfilesync_filename_options)) will throw the
31 error. The act of *throwing* a value (in this case, the error) turns the value
32 into an **exception**. Exceptions may be caught using the `try { } catch(err)
35 Asynchronous APIs have **two** mechanisms for error propagation; one mechanism
36 for APIs that represent a single operation, and one for APIs that represent
37 multiple operations over time.
43 The other mechanism for providing errors is the "error" event. This is
44 typically used by [stream-based](stream.html) and [event emitter-based](events.html#events_class_events_eventemitter) APIs, which
45 themselves represent a series of asynchronous operations over time (versus a
46 single operation that may pass or fail). If no "error" event handler is
47 attached to the source of the error, the error will be thrown. At this point,
48 it will crash the process as an unhandled exception unless [domains](domain.html) are
49 employed appropriately or [process.on('uncaughtException')](process.html#process_event_uncaughtexception) has a handler.
52 var net = require('net');
54 var connection = net.connect('localhost');
56 // adding an "error" event handler to a stream:
57 connection.on('error', function(err) {
58 // if the connection is reset by the server, or if it can't
59 // connect at all, or on any sort of error encountered by
60 // the connection, the error will be sent here.
64 connection.pipe(process.stdout);
67 The "throw when no error handlers are attached behavior" is not limited to APIs
68 provided by Node.js -- even user created event emitters and streams will throw
69 errors when no error handlers are attached. An example:
72 var EventEmitter = require('events');
74 var ee = new EventEmitter();
76 setImmediate(function() {
77 // this will crash the process because no "error" event
78 // handler has been added.
79 ee.emit('error', new Error('This will crash'));
83 As with node style callbacks, errors generated this way *cannot* be intercepted
84 by `try { } catch(err) { }` -- they happen *after* the calling code has already
87 ### Node style callbacks
91 Single operation APIs take "node style callbacks" -- a
92 function provided to the API as an argument. The node style callback takes
93 at least **one** argument -- `error` -- that will either be `null` (if no error
94 was encountered) or an `Error` instance. For instance:
97 var fs = require('fs');
99 fs.readFile('/some/file/that/does-not-exist', function nodeStyleCallback(err, data) {
100 console.log(err) // Error: ENOENT
101 console.log(data) // undefined / null
104 fs.readFile('/some/file/that/does-exist', function(err, data) {
105 console.log(err) // null
106 console.log(data) // <Buffer: ba dd ca fe>
110 Note that `try { } catch(err) { }` **cannot** intercept errors generated by
111 asynchronous APIs. A common mistake for beginners is to try to use `throw`
112 inside their node style callback:
115 // THIS WILL NOT WORK:
116 var fs = require('fs');
119 fs.readFile('/some/file/that/does-not-exist', function(err, data) {
120 // mistaken assumption: throwing here...
126 // ... will be caught here -- this is incorrect!
127 console.log(err); // Error: ENOENT
131 This will not work! By the time the node style callback has been called, the
132 surrounding code (including the `try { } catch(err) { }` will have already
133 exited. Throwing an error inside a node style callback **will crash the process** in most cases.
134 If [domains](domain.html) are enabled, they may intercept the thrown error; similarly, if a
135 handler has been added to `process.on('uncaughtException')`, it will intercept
142 JavaScript errors typically denote that an API is being used incorrectly, or that
143 there is a problem with the program as written.
149 A general error object. Unlike other error objects, `Error` instances do not
150 denote any specific circumstance of why the error occurred. Errors capture a
151 "stack trace" detailing the point in the program at which they were
152 instantiated, and may provide a description of the error.
154 **Note**: Node.js will generate this class of error to encapsulate system
155 errors as well as plain JavaScript errors.
157 #### new Error(message)
159 Instantiates a new Error object and sets its `.message` property to the provided
160 message. Its `.stack` will represent the point in the program at which `new Error`
161 was called. Stack traces are subject to [V8's stack trace API](https://code.google.com/p/v8-wiki/wiki/JavaScriptStackTraceApi).
162 Stack traces only extend to the beginning of synchronous code execution, *or* a number of frames given by
163 `Error.stackTraceLimit`, whichever is smaller.
165 #### Error.captureStackTrace(targetObject[, constructorOpt])
167 Creates a `.stack` property on `targetObject`, which when accessed returns
168 a string representing the location in the program at which `Error.captureStackTrace`
174 Error.captureStackTrace(myObject);
176 myObject.stack // similar to `new Error().stack`
179 The first line of the trace, instead of being prefixed with `ErrorType:
180 message`, will be the result of `targetObject.toString()`.
182 `constructorOpt` optionally accepts a function. If given, all frames above
183 `constructorOpt`, including `constructorOpt`, will be omitted from the generated
186 This is useful for hiding implementation details of error generation from the
187 end user. A common way of using this parameter is to pass the current Error
193 Error.captureStackTrace(this, MyError);
196 // without passing MyError to captureStackTrace, the MyError
197 // frame would should up in the .stack property. by passing
198 // the constructor, we omit that frame and all frames above it.
203 #### Error.stackTraceLimit
205 Property that determines the number of stack frames collected by a stack trace
206 (whether generated by `new Error().stack` or `Error.captureStackTrace(obj)`).
208 The initial value is `10`. It may be set to any valid JavaScript number, which
209 will affect any stack trace captured *after* the value has been changed. If set
210 to a non-number value, stack traces will not capture any frames and will report
211 `undefined` on access.
215 A string of the value passed to `Error()` upon instantiation. The message will
216 also appear in the first line of the stack trace of the error. Changing this
217 property *may not* change the first line of the stack trace.
221 A property that, when **accessed**, returns a string representing the point in the program
222 at which this error was instantiated. An example stacktrace follows:
224 Error: Things keep happening!
225 at /home/gbusey/file.js:525:2
226 at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
227 at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
228 at increaseSynergy (/home/gbusey/actors.js:701:6)
230 The first line is formatted as `<error class name>: <error message>`, and it is followed
231 by a series of stack frames (each line beginning with "at "). Each frame describes
232 a call site in the program that lead to the error being generated. V8 attempts to
233 display a name for each function (by variable name, function name, or object
234 method name), but occasionally it will not be able to find a suitable name. If
235 V8 cannot determine a name for the function, only location information will be
236 displayed for that frame. Otherwise, the determined function name will be displayed
237 with location information appended in parentheses.
239 Frames are **only** generated for JavaScript functions. If, for example, execution
240 synchronously passes through a C++ addon function called `cheetahify`, which itself
241 calls a JavaScript function, the frame representing the `cheetahify` call will **not**
242 be present in stacktraces:
245 var cheetahify = require('./native-binding.node');
247 function makeFaster() {
248 // cheetahify *synchronously* calls speedy.
249 cheetahify(function speedy() {
250 throw new Error('oh no!');
254 makeFaster(); // will throw:
255 // /home/gbusey/file.js:6
256 // throw new Error('oh no!');
259 // at speedy (/home/gbusey/file.js:6:11)
260 // at makeFaster (/home/gbusey/file.js:5:3)
261 // at Object.<anonymous> (/home/gbusey/file.js:10:1)
262 // at Module._compile (module.js:456:26)
263 // at Object.Module._extensions..js (module.js:474:10)
264 // at Module.load (module.js:356:32)
265 // at Function.Module._load (module.js:312:12)
266 // at Function.Module.runMain (module.js:497:10)
267 // at startup (node.js:119:16)
271 The location information will be one of:
273 * `native`, if the frame represents a call internal to V8 (as in `[].forEach`).
274 * `plain-filename.js:line:column`, if the frame represents a call internal to Node.js.
275 * `/absolute/path/to/file.js:line:column`, if the frame represents a call in a user program, or its dependencies.
277 It is important to note that the string representing the stacktrace is only
278 generated on **access**: it is lazily generated.
280 The number of frames captured by the stack trace is bounded by the smaller of
281 `Error.stackTraceLimit` or the number of available frames on the current event
284 System-level errors are generated as augmented Error instances, which are detailed
285 [below](#errors_system_errors).
287 ### Class: RangeError
289 A subclass of Error that indicates that a provided argument was not within the
290 set or range of acceptable values for a function; whether that be a numeric
291 range, or outside the set of options for a given function parameter. An example:
294 require('net').connect(-1); // throws RangeError, port should be > 0 && < 65536
297 Node.js will generate and throw RangeError instances *immediately* -- they are a form
298 of argument validation.
300 ### Class: ReferenceError
302 A subclass of Error that indicates that an attempt is being made to access a variable
303 that is not defined. Most commonly it indicates a typo, or an otherwise broken program.
304 While client code may generate and propagate these errors, in practice only V8 will do
308 doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program.
311 ReferenceError instances will have an `.arguments` member that is an array containing
312 one element -- a string representing the variable that was not defined.
318 err.arguments[0] === 'doesNotExist';
322 Unless the userland program is dynamically generating and running code,
323 ReferenceErrors should always be considered a bug in the program, or its
326 ### Class: SyntaxError
328 A subclass of Error that indicates that a program is not valid JavaScript.
329 These errors may only be generated and propagated as a result of code
330 evaluation. Code evaluation may happen as a result of `eval`, `Function`,
331 `require`, or [vm](vm.html). These errors are almost always indicative of a broken
336 require("vm").runInThisContext("binary ! isNotOk");
338 // err will be a SyntaxError
342 SyntaxErrors are unrecoverable from the context that created them – they may only be caught
347 A subclass of Error that indicates that a provided argument is not an allowable
348 type. For example, passing a function to a parameter which expects a string would
349 be considered a TypeError.
352 require('url').parse(function() { }); // throws TypeError, since it expected a string
355 Node.js will generate and throw TypeError instances *immediately* -- they are a form
356 of argument validation.
358 ### Exceptions vs. Errors
362 A JavaScript "exception" is a value that is thrown as a result of an invalid operation or
363 as the target of a `throw` statement. While it is not required that these values inherit from
364 `Error`, all exceptions thrown by Node.js or the JavaScript runtime *will* be instances of Error.
366 Some exceptions are *unrecoverable* at the JavaScript layer. These exceptions will always bring
367 down the process. These are usually failed `assert()` checks or `abort()` calls in the C++ layer.
371 System errors are generated in response to a program's runtime environment.
372 Ideally, they represent operational errors that the program needs to be able to
373 react to. They are generated at the syscall level: an exhaustive list of error
374 codes and their meanings is available by running `man 2 intro` or `man 3 errno`
375 on most Unices; or [online](http://man7.org/linux/man-pages/man3/errno.3.html).
377 In Node.js, system errors are represented as augmented Error objects -- not full
378 subclasses, but instead an error instance with added members.
380 ### Class: System Error
385 A string representing the error code, which is always `E` followed by capital
386 letters, and may be referenced in `man 2 intro`.
390 A string representing the [syscall](http://man7.org/linux/man-pages/man2/syscall.2.html) that failed.
392 ### Common System Errors
394 This list is **not exhaustive**, but enumerates many of the common system errors when
395 writing a Node.js program. An exhaustive list may be found [here](http://man7.org/linux/man-pages/man3/errno.3.html).
397 #### EACCES: Permission denied
399 An attempt was made to access a file in a way forbidden by its file access
402 #### EADDRINUSE: Address already in use
404 An attempt to bind a server ([net](net.html), [http](http.html), or [https](https.html)) to a local
405 address failed due to another server on the local system already occupying
408 #### ECONNREFUSED: Connection refused
410 No connection could be made because the target machine actively refused
411 it. This usually results from trying to connect to a service that is inactive
414 #### ECONNRESET: Connection reset by peer
416 A connection was forcibly closed by a peer. This normally results
417 from a loss of the connection on the remote socket due to a timeout
418 or reboot. Commonly encountered via the [http](http.html) and [net](net.html) modules.
420 #### EEXIST: File exists
422 An existing file was the target of an operation that required that the target
425 #### EISDIR: Is a directory
427 An operation expected a file, but the given pathname was a directory.
429 #### EMFILE: Too many open files in system
431 Maximum number of [file descriptors](http://en.wikipedia.org/wiki/File_descriptor) allowable on the system has
432 been reached, and requests for another descriptor cannot be fulfilled until
433 at least one has been closed.
435 Commonly encountered when opening many files at once in parallel, especially
436 on systems (in particular, OS X) where there is a low file descriptor limit
437 for processes. To remedy a low limit, run `ulimit -n 2048` in the same shell
438 that will run the Node.js process.
440 #### ENOENT: No such file or directory
442 Commonly raised by [fs](fs.html) operations; a component of the specified pathname
443 does not exist -- no entity (file or directory) could be found by the given path.
445 #### ENOTDIR: Not a directory
447 A component of the given pathname existed, but was not a directory as expected.
448 Commonly raised by [fs.readdir](fs.html#fs_fs_readdir_path_callback).
450 #### ENOTEMPTY: Directory not empty
452 A directory with entries was the target of an operation that requires
453 an empty directory -- usually [fs.unlink](fs.html#fs_fs_unlink_path_callback).
455 #### EPERM: Operation not permitted
457 An attempt was made to perform an operation that requires appropriate
460 #### EPIPE: Broken pipe
462 A write on a pipe, socket, or FIFO for which there is no process to read the
463 data. Commonly encountered at the [net](net.html) and [http](http.html) layers, indicative that
464 the remote side of the stream being written to has been closed.
466 #### ETIMEDOUT: Operation timed out
468 A connect or send request failed because the connected party did not properly
469 respond after a period of time. Usually encountered by [http](http.html) or [net](net.html) --
470 often a sign that a connected socket was not `.end()`'d appropriately.