823e9361901cb133b1116238b636d114271f51da
[platform/upstream/nodejs.git] / doc / api / errors.markdown
1 # Errors
2
3 <!--type=misc-->
4
5 Applications running in Node.js will generally experience four categories of
6 errors:
7
8 - Standard JavaScript errors such as:
9   - [`EvalError`][]: thrown when a call to `eval()` fails.
10   - [`SyntaxError`][]: thrown in response to improper JavaScript language
11     syntax.
12   - [`RangeError`][]: thrown when a value is not within an expected range
13   - [`ReferenceError`][]: thrown when using undefined variables
14   - [`TypeError`][]: thrown when passing arguments of the wrong type
15   - [`URIError`][]: thrown when a global URI handling function is misused.
16 - System errors triggered by underlying operating system constraints such
17   as attempting to open a file that does not exist, attempting to send data
18   over a closed socket, etc;
19 - And User-specified errors triggered by application code.
20 - Assertion Errors are a special class of error that can be triggered whenever
21   Node.js detects an exceptional logic violation that should never occur. These
22   are raised typically by the `assert` module.
23
24 All JavaScript and System errors raised by Node.js inherit from, or are
25 instances of, the standard JavaScript [`Error`][] class and are guaranteed
26 to provide *at least* the properties available on that class.
27
28 ## Error Propagation and Interception
29
30 <!--type=misc-->
31
32 Node.js supports several mechanisms for propagating and handling errors that
33 occur while an application is running. How these errors are reported and
34 handled depends entirely on the type of Error and the style of the API that is
35 called.
36
37 All JavaScript errors are handled as exceptions that *immediately* generate
38 and throw an error using the standard JavaScript `throw` mechanism. These
39 are handled using the [`try / catch` construct][] provided by the JavaScript
40 language.
41
42     // Throws with a ReferenceError because z is undefined
43     try {
44       const m = 1;
45       const n = m + z;
46     } catch (err) {
47       // Handle the error here.
48     }
49
50 Any use of the JavaScript `throw` mechanism will raise an exception that
51 *must* be handled using `try / catch` or the Node.js process will exit
52 immediately.
53
54 With few exceptions, _Synchronous_ APIs (any blocking method that does not
55 accept a `callback` function, such as [`fs.readFileSync`][]), will use `throw`
56 to report errors.
57
58 Errors that occur within _Asynchronous APIs_ may be reported in multiple ways:
59
60 - Most asynchronous methods that accept a `callback` function will accept an
61   `Error` object passed as the first argument to that function. If that first
62   argument is not `null` and is an instance of `Error`, then an error occurred
63   that should be handled.
64
65   ```
66   const fs = require('fs');
67   fs.readFile('a file that does not exist', (err, data) => {
68     if (err) {
69       console.error('There was an error reading the file!', err);
70       return;
71     }
72     // Otherwise handle the data
73   });
74   ```
75 - When an asynchronous method is called on an object that is an `EventEmitter`,
76   errors can be routed to that object's `'error'` event.
77
78   ```
79   const net = require('net');
80   const connection = net.connect('localhost');
81
82   // Adding an 'error' event handler to a stream:
83   connection.on('error', (err) => {
84     // If the connection is reset by the server, or if it can't
85     // connect at all, or on any sort of error encountered by
86     // the connection, the error will be sent here.
87     console.error(err);
88   });
89
90   connection.pipe(process.stdout);
91   ```
92
93 - A handful of typically asynchronous methods in the Node.js API may still
94   use the `throw` mechanism to raise exceptions that must be handled using
95   `try / catch`. There is no comprehensive list of such methods; please
96   refer to the documentation of each method to determine the appropriate
97   error handling mechanism required.
98
99 The use of the `'error'` event mechanism is most common for [stream-based][]
100 and [event emitter-based][] APIs, which themselves represent a series of
101 asynchronous operations over time (as opposed to a single operation that may
102 pass or fail).
103
104 For *all* `EventEmitter` objects, if an `'error'` event handler is not
105 provided, the error will be thrown, causing the Node.js process to report an
106 unhandled exception and  crash unless either: The [`domain`][] module is used
107 appropriately or a handler has been registered for the
108 [`process.on('uncaughtException')`][] event.
109
110     const EventEmitter = require('events');
111     const ee = new EventEmitter();
112
113     setImmediate(() => {
114       // This will crash the process because no 'error' event
115       // handler has been added.
116       ee.emit('error', new Error('This will crash'));
117     });
118
119 Errors generated in this way *cannot* be intercepted using `try / catch` as
120 they are thrown *after* the calling code has already exited.
121
122 Developers must refer to the documentation for each method to determine
123 exactly how errors raised by those methods are propagated.
124
125 ### Node.js style callbacks
126
127 <!--type=misc-->
128
129 Most asynchronous methods exposed by the Node.js core API follow an idiomatic
130 pattern  referred to as a "Node.js style callback". With this pattern, a
131 callback function is passed to the method as an argument. When the operation
132 either completes or an error is raised, the callback function is called with
133 the Error object (if any) passed as the first argument. If no error was raised,
134 the first argument will be passed as `null`.
135
136     const fs = require('fs');
137
138     function nodeStyleCallback(err, data) {
139      if (err) {
140        console.error('There was an error', err);
141        return;
142      }
143      console.log(data);
144     }
145
146     fs.readFile('/some/file/that/does-not-exist', nodeStyleCallback);
147     fs.readFile('/some/file/that/does-exist', nodeStyleCallback)
148
149 The JavaScript `try / catch` mechanism **cannot** be used to intercept errors
150 generated by asynchronous APIs.  A common mistake for beginners is to try to
151 use `throw` inside a Node.js style callback:
152
153     // THIS WILL NOT WORK:
154     const fs = require('fs');
155
156     try {
157       fs.readFile('/some/file/that/does-not-exist', (err, data) => {
158         // mistaken assumption: throwing here...
159         if (err) {
160           throw err;
161         }
162       });
163     } catch(err) {
164       // This will not catch the throw!
165       console.log(err);
166     }
167
168 This will not work because the callback function passed to `fs.readFile()` is
169 called asynchronously. By the time the callback has been called, the
170 surrounding code (including the `try { } catch(err) { }` block will have
171 already exited. Throwing an error inside the callback **can crash the Node.js
172 process** in most cases. If [domains][] are enabled, or a handler has been
173 registered with `process.on('uncaughtException')`, such errors can be
174 intercepted.
175
176 ## Class: Error
177
178 <!--type=class-->
179
180 A generic JavaScript `Error` object that does not denote any specific
181 circumstance of why the error occurred. `Error` objects capture a "stack trace"
182 detailing the point in the code at which the `Error` was instantiated, and may
183 provide a text description of the error.
184
185 All errors generated by Node.js, including all System and JavaScript errors,
186 will either be instances of, or inherit from, the `Error` class.
187
188 ### new Error(message)
189
190 Creates a new `Error` object and sets the `error.message` property to the
191 provided text message. If an object is passed as `message`, the text message
192 is generated by calling `message.toString()`. The `error.stack` property will
193 represent the point in the code at which `new Error()` was called. Stack traces
194 are dependent on [V8's stack trace API][]. Stack traces extend only to either
195 (a) the beginning of  *synchronous code execution*, or (b) the number of frames
196 given by the property `Error.stackTraceLimit`, whichever is smaller.
197
198 ### Error.captureStackTrace(targetObject[, constructorOpt])
199
200 Creates a `.stack` property on `targetObject`, which when accessed returns
201 a string representing the location in the code at which
202 `Error.captureStackTrace()` was called.
203
204     const myObject = {};
205     Error.captureStackTrace(myObject);
206     myObject.stack  // similar to `new Error().stack`
207
208 The first line of the trace, instead of being prefixed with `ErrorType:
209 message`, will be the result of calling `targetObject.toString()`.
210
211 The optional `constructorOpt` argument accepts a function. If given, all frames
212 above `constructorOpt`, including `constructorOpt`, will be omitted from the
213 generated stack trace.
214
215 The `constructorOpt` argument is useful for hiding implementation
216 details of error generation from an end user. For instance:
217
218     function MyError() {
219       Error.captureStackTrace(this, MyError);
220     }
221
222     // Without passing MyError to captureStackTrace, the MyError
223     // frame would should up in the .stack property. by passing
224     // the constructor, we omit that frame and all frames above it.
225     new MyError().stack
226
227 ### Error.stackTraceLimit
228
229 The `Error.stackTraceLimit` property specifies the number of stack frames
230 collected by a stack trace (whether generated by `new Error().stack` or
231 `Error.captureStackTrace(obj)`).
232
233 The default value is `10` but may be set to any valid JavaScript number. Changes
234 will affect any stack trace captured *after* the value has been changed.
235
236 If set to a non-number value, or set to a negative number, stack traces will
237 not capture any frames.
238
239 #### error.message
240
241 Returns the string description of error as set by calling `new Error(message)`.
242 The `message` passed to the constructor will also appear in the first line of
243 the stack trace of the `Error`, however changing this property after the
244 `Error` object is created *may not* change the first line of the stack trace.
245
246     const err = new Error('The message');
247     console.log(err.message);
248       // Prints: The message
249
250 #### error.stack
251
252 Returns a string describing the point in the code at which the `Error` was
253 instantiated.
254
255 For example:
256
257     Error: Things keep happening!
258        at /home/gbusey/file.js:525:2
259        at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)
260        at Actor.<anonymous> (/home/gbusey/actors.js:400:8)
261        at increaseSynergy (/home/gbusey/actors.js:701:6)
262
263 The first line is formatted as `<error class name>: <error message>`, and
264 is followed by a series of stack frames (each line beginning with "at ").
265 Each frame describes a call site within the code that lead to the error being
266 generated. V8 attempts to display a name for each function (by variable name,
267 function name, or object method name), but occasionally it will not be able to
268 find a suitable name. If V8 cannot determine a name for the function, only
269 location information will be displayed for that frame. Otherwise, the
270 determined function name will be displayed with location information appended
271 in parentheses.
272
273 It is important to note that frames are **only** generated for JavaScript
274 functions. If, for example, execution synchronously passes through a C++ addon
275 function called `cheetahify`, which itself calls a JavaScript function, the
276 frame representing the `cheetahify` call will **not** be present in the stack
277 traces:
278
279     const cheetahify = require('./native-binding.node');
280
281     function makeFaster() {
282       // cheetahify *synchronously* calls speedy.
283       cheetahify(function speedy() {
284         throw new Error('oh no!');
285       });
286     }
287
288     makeFaster(); // will throw:
289       // /home/gbusey/file.js:6
290       //     throw new Error('oh no!');
291       //           ^
292       // Error: oh no!
293       //     at speedy (/home/gbusey/file.js:6:11)
294       //     at makeFaster (/home/gbusey/file.js:5:3)
295       //     at Object.<anonymous> (/home/gbusey/file.js:10:1)
296       //     at Module._compile (module.js:456:26)
297       //     at Object.Module._extensions..js (module.js:474:10)
298       //     at Module.load (module.js:356:32)
299       //     at Function.Module._load (module.js:312:12)
300       //     at Function.Module.runMain (module.js:497:10)
301       //     at startup (node.js:119:16)
302       //     at node.js:906:3
303
304 The location information will be one of:
305
306 * `native`, if the frame represents a call internal to V8 (as in `[].forEach`).
307 * `plain-filename.js:line:column`, if the frame represents a call internal
308    to Node.js.
309 * `/absolute/path/to/file.js:line:column`, if the frame represents a call in
310   a user program, or its dependencies.
311
312 The string representing the stack trace is lazily generated when the
313 `error.stack` property is **accessed**.
314
315 The number of frames captured by the stack trace is bounded by the smaller of
316 `Error.stackTraceLimit` or the number of available frames on the current event
317 loop tick.
318
319 System-level errors are generated as augmented `Error` instances, which are
320 detailed [below](#errors_system_errors).
321
322 ## Class: RangeError
323
324 A subclass of `Error` that indicates that a provided argument was not within the
325 set or range of acceptable values for a function; whether that is a numeric
326 range, or outside the set of options for a given function parameter.
327
328 For example:
329
330     require('net').connect(-1);
331       // throws RangeError, port should be > 0 && < 65536
332
333 Node.js will generate and throw `RangeError` instances *immediately* as a form
334 of argument validation.
335
336 ## Class: ReferenceError
337
338 A subclass of `Error` that indicates that an attempt is being made to access a
339 variable that is not defined. Such errors commonly indicate typos in code, or
340 an otherwise broken program.
341
342 While client code may generate and propagate these errors, in practice, only V8
343 will do so.
344
345     doesNotExist;
346       // throws ReferenceError, doesNotExist is not a variable in this program.
347
348 `ReferenceError` instances will have an `error.arguments` property whose value
349 is an array containing a single element: a string representing the variable
350 that was not defined.
351
352     const assert = require('assert');
353     try {
354       doesNotExist;
355     } catch(err) {
356       assert(err.arguments[0], 'doesNotExist');
357     }
358
359 Unless an application is dynamically generating and running code,
360 `ReferenceError` instances should always be considered a bug in the code
361 or its dependencies.
362
363 ## Class: SyntaxError
364
365 A subclass of `Error` that indicates that a program is not valid JavaScript.
366 These errors may only be generated and propagated as a result of code
367 evaluation. Code evaluation may happen as a result of `eval`, `Function`,
368 `require`, or [vm][]. These errors are almost always indicative of a broken
369 program.
370
371     try {
372       require('vm').runInThisContext('binary ! isNotOk');
373     } catch(err) {
374       // err will be a SyntaxError
375     }
376
377 `SyntaxError` instances are unrecoverable in the context that created them –
378 they may only be caught by other contexts.
379
380 ## Class: TypeError
381
382 A subclass of `Error` that indicates that a provided argument is not an
383 allowable type. For example, passing a function to a parameter which expects a
384 string would be considered a TypeError.
385
386     require('url').parse(function() { });
387       // throws TypeError, since it expected a string
388
389 Node.js will generate and throw `TypeError` instances *immediately* as a form
390 of argument validation.
391
392 ## Exceptions vs. Errors
393
394 <!--type=misc-->
395
396 A JavaScript exception is a value that is thrown as a result of an invalid
397 operation or as the target of a `throw` statement. While it is not required
398 that these values are instances of `Error` or classes which inherit from
399 `Error`, all exceptions thrown by Node.js or the JavaScript runtime *will* be
400 instances of Error.
401
402 Some exceptions are *unrecoverable* at the JavaScript layer. Such exceptions
403 will *always* cause the Node.js process to crash. Examples include `assert()`
404 checks or `abort()` calls in the C++ layer.
405
406 ## System Errors
407
408 System errors are generated when exceptions occur within the program's
409 runtime environment. Typically, these are operational errors that occur
410 when an application violates an operating system constraint such as attempting
411 to read a file that does not exist or when the user does not have sufficient
412 permissions.
413
414 System errors are typically generated at the syscall level: an exhaustive list
415 of error codes and their meanings is available by running `man 2 intro` or
416 `man 3 errno` on most Unices; or [online][].
417
418 In Node.js, system errors are represented as augmented `Error` objects with
419 added properties.
420
421 ### Class: System Error
422
423 #### error.code
424 #### error.errno
425
426 Returns a string representing the error code, which is always `E` followed by
427 a sequence of capital letters, and may be referenced in `man 2 intro`.
428
429 The properties `error.code` and `error.errno` are aliases of one another and
430 return the same value.
431
432 #### error.syscall
433
434 Returns a string describing the [syscall][] that failed.
435
436 ### Common System Errors
437
438 This list is **not exhaustive**, but enumerates many of the common system
439 errors encountered when writing a Node.js program. An exhaustive list may be
440 found [here][online].
441
442 - `EACCES` (Permission denied): An attempt was made to access a file in a way
443   forbidden by its file access permissions.
444
445 - `EADDRINUSE` (Address already in use):  An attempt to bind a server
446   ([`net`][], [`http`][], or [`https`][]) to a local address failed due to
447   another server on the local system already occupying that address.
448
449 - `ECONNREFUSED` (Connection refused): No connection could be made because the
450   target machine actively refused it. This usually results from trying to
451   connect to a service that is inactive on the foreign host.
452
453 - `ECONNRESET` (Connection reset by peer): A connection was forcibly closed by
454   a peer. This normally results from a loss of the connection on the remote
455   socket due to a timeout or reboot. Commonly encountered via the [`http`][]
456   and [`net`][] modules.
457
458 - `EEXIST` (File exists): An existing file was the target of an operation that
459   required that the target not exist.
460
461 - `EISDIR` (Is a directory): An operation expected a file, but the given
462   pathname was a directory.
463
464 - `EMFILE` (Too many open files in system): Maximum number of
465   [file descriptors][] allowable on the system has been reached, and
466   requests for another descriptor cannot be fulfilled until at least one
467   has been closed. This is encountered when opening many files at once in
468   parallel, especially on systems (in particular, OS X) where there is a low
469   file descriptor limit for processes. To remedy a low limit, run
470   `ulimit -n 2048` in the same shell that will run the Node.js process.
471
472 - `ENOENT` (No such file or directory): Commonly raised by [`fs`][] operations
473   to indicate that a component of the specified pathname does not exist -- no
474   entity (file or directory) could be found by the given path.
475
476 - `ENOTDIR` (Not a directory): A component of the given pathname existed, but
477   was not a directory as expected. Commonly raised by [`fs.readdir`][].
478
479 - `ENOTEMPTY` (Directory not empty): A directory with entries was the target
480   of an operation that requires an empty directory -- usually [`fs.unlink`][].
481
482 - `EPERM` (Operation not permitted): An attempt was made to perform an
483   operation that requires elevated privileges.
484
485 - `EPIPE` (Broken pipe): A write on a pipe, socket, or FIFO for which there is
486   no process to read the data. Commonly encountered at the [`net`][] and
487   [`http`][] layers, indicative that the remote side of the stream being
488   written to has been closed.
489
490 - `ETIMEDOUT` (Operation timed out): A connect or send request failed because
491   the connected party did not properly respond after a period of time. Usually
492   encountered by [`http`][] or [`net`][] -- often a sign that a `socket.end()`
493   was not properly called.
494
495 [`Error`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
496 [`fs.readdir`]: fs.html#fs_fs_readdir_path_callback
497 [`fs.readFileSync`]: fs.html#fs_fs_readfilesync_file_options
498 [`fs.unlink`]: fs.html#fs_fs_unlink_path_callback
499 [`fs`]: fs.html
500 [`http`]: http.html
501 [`https`]: https.html
502 [`net`]: net.html
503 [`process.on('uncaughtException')`]: process.html#process_event_uncaughtexception
504 [`try / catch` construct]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
505 [`try { } catch(err) { }`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
506 [below]: #errors_error_propagation_and_interception
507 [domains]: domain.html
508 [event emitter-based]: events.html#events_class_events_eventemitter
509 [file descriptors]: https://en.wikipedia.org/wiki/File_descriptor
510 [online]: http://man7.org/linux/man-pages/man3/errno.3.html
511 [stream-based]: stream.html
512 [syscall]: http://man7.org/linux/man-pages/man2/syscall.2.html
513 [V8's stack trace API]: https://github.com/v8/v8/wiki/Stack-Trace-API
514 [vm]: vm.html
515 [`SyntaxError`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError
516 [`ReferenceError`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError
517 [`TypeError`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
518 [`domain`]: domain.html