doc: sort globals alphabetically
[platform/upstream/nodejs.git] / doc / api / errors.markdown
1 # Errors
2
3 <!--type=misc-->
4
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
8 class.
9
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.
15
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).
20
21 ## Error Propagation and Interception
22
23 <!--type=misc-->
24
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.
28
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)
33 { }` construct.
34
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.
38
39 ### Error events
40
41 <!--type=misc-->
42
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.
50
51 ```javascript
52 var net = require('net');
53
54 var connection = net.connect('localhost');
55
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.
61   console.error(err);
62 });
63
64 connection.pipe(process.stdout);
65 ```
66
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:
70
71 ```javascript
72 var EventEmitter = require('events');
73
74 var ee = new EventEmitter();
75
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'));
80 });
81 ```
82
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
85 exited.
86
87 ### Node style callbacks
88
89 <!--type=misc-->
90
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:
95
96 ```javascript
97 var fs = require('fs');
98
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
102 });
103
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>
107 })
108 ```
109
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:
113
114 ```javascript
115 // THIS WILL NOT WORK:
116 var fs = require('fs');
117
118 try {
119   fs.readFile('/some/file/that/does-not-exist', function(err, data) {
120     // mistaken assumption: throwing here...
121     if (err) {
122       throw err;
123     }
124   });
125 } catch(err) {
126   // ... will be caught here -- this is incorrect!
127   console.log(err); // Error: ENOENT
128 }
129 ```
130
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
136 the error.
137
138 ## JavaScript Errors
139
140 <!--type=misc-->
141
142 JavaScript errors typically denote that an API is being used incorrectly, or that
143 there is a problem with the program as written.
144
145 ### Class: Error
146
147 <!--type=class-->
148
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.
153
154 **Note**: Node.js will generate this class of error to encapsulate system
155 errors as well as plain JavaScript errors.
156
157 #### new Error(message)
158
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.
164
165 #### Error.captureStackTrace(targetObject[, constructorOpt])
166
167 Creates a `.stack` property on `targetObject`, which when accessed returns
168 a string representing the location in the program at which `Error.captureStackTrace`
169 was called.
170
171 ```javascript
172 var myObject = {};
173
174 Error.captureStackTrace(myObject);
175
176 myObject.stack  // similar to `new Error().stack`
177 ```
178
179 The first line of the trace, instead of being prefixed with `ErrorType:
180 message`, will be the result of `targetObject.toString()`.
181
182 `constructorOpt` optionally accepts a function. If given, all frames above
183 `constructorOpt`, including `constructorOpt`, will be omitted from the generated
184 stack trace.
185
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
188 constructor to it:
189
190 ```javascript
191
192 function MyError() {
193   Error.captureStackTrace(this, MyError);
194 }
195
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.
199 new MyError().stack
200
201 ```
202
203 #### Error.stackTraceLimit
204
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)`).
207
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.
212
213 #### error.message
214
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.
218
219 #### error.stack
220
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:
223
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)
229
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.
238
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:
243
244 ```javascript
245 var cheetahify = require('./native-binding.node');
246
247 function makeFaster() {
248   // cheetahify *synchronously* calls speedy.
249   cheetahify(function speedy() {
250     throw new Error('oh no!');
251   });
252 }
253
254 makeFaster(); // will throw:
255 // /home/gbusey/file.js:6
256 //     throw new Error('oh no!');
257 //           ^
258 // 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)
268 //     at node.js:906:3
269 ```
270
271 The location information will be one of:
272
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.
276
277 It is important to note that the string representing the stacktrace is only
278 generated on **access**: it is lazily generated.
279
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
282 loop tick.
283
284 System-level errors are generated as augmented Error instances, which are detailed
285 [below](#errors_system_errors).
286
287 ### Class: RangeError
288
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:
292
293 ```javascript
294 require('net').connect(-1);  // throws RangeError, port should be > 0 && < 65536
295 ```
296
297 Node.js will generate and throw RangeError instances *immediately* -- they are a form
298 of argument validation.
299
300 ### Class: ReferenceError
301
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
305 so.
306
307 ```javascript
308 doesNotExist; // throws ReferenceError, doesNotExist is not a variable in this program.
309 ```
310
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.
313
314 ```javascript
315 try {
316   doesNotExist;
317 } catch(err) {
318   err.arguments[0] === 'doesNotExist';
319 }
320 ```
321
322 Unless the userland program is dynamically generating and running code,
323 ReferenceErrors should always be considered a bug in the program, or its
324 dependencies.
325
326 ### Class: SyntaxError
327
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
332 program.
333
334 ```javascript
335 try {
336   require("vm").runInThisContext("binary ! isNotOk");
337 } catch(err) {
338   // err will be a SyntaxError
339 }
340 ```
341
342 SyntaxErrors are unrecoverable from the context that created them – they may only be caught
343 by other contexts.
344
345 ### Class: TypeError
346
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.
350
351 ```javascript
352 require('url').parse(function() { }); // throws TypeError, since it expected a string
353 ```
354
355 Node.js will generate and throw TypeError instances *immediately* -- they are a form
356 of argument validation.
357
358 ### Exceptions vs. Errors
359
360 <!--type=misc-->
361
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.
365
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.
368
369 ## System Errors
370
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).
376
377 In Node.js, system errors are represented as augmented Error objects -- not full
378 subclasses, but instead an error instance with added members.
379
380 ### Class: System Error
381
382 #### error.code
383 #### error.errno
384
385 A string representing the error code, which is always `E` followed by capital
386 letters, and may be referenced in `man 2 intro`.
387
388 #### error.syscall
389
390 A string representing the [syscall](http://man7.org/linux/man-pages/man2/syscall.2.html) that failed.
391
392 ### Common System Errors
393
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).
396
397 #### EACCES: Permission denied
398
399 An attempt was made to access a file in a way forbidden by its file access
400 permissions.
401
402 #### EADDRINUSE: Address already in use
403
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
406 that address.
407
408 #### ECONNREFUSED: Connection refused
409
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
412 on the foreign host.
413
414 #### ECONNRESET: Connection reset by peer
415
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.
419
420 #### EEXIST: File exists
421
422 An existing file was the target of an operation that required that the target
423 not exist.
424
425 #### EISDIR: Is a directory
426
427 An operation expected a file, but the given pathname was a directory.
428
429 #### EMFILE: Too many open files in system
430
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.
434
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.
439
440 #### ENOENT: No such file or directory
441
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.
444
445 #### ENOTDIR: Not a directory
446
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).
449
450 #### ENOTEMPTY: Directory not empty
451
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).
454
455 #### EPERM: Operation not permitted
456
457 An attempt was made to perform an operation that requires appropriate
458 privileges.
459
460 #### EPIPE: Broken pipe
461
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.
465
466 #### ETIMEDOUT: Operation timed out
467
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.