Errors
Applications running in Node.js will generally experience the following categories of errors:- Standard JavaScript errors such as
EvalError,SyntaxError,RangeError,ReferenceError,TypeError, andURIError - Standard
DOMExceptions - System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist or attempting to send data over a closed socket
AssertionErrors are a special class of error that can be triggered when Node.js detects an exceptional logic violation that should never occur. These are raised typically by thenode:assertmodule- User-specified errors triggered by application code
Error class and are guaranteed to provide at least the properties available on that class.
Error Propagation and Interception
Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and handled depends entirely on the type ofError and the style of the API that is called.
Synchronous APIs
All JavaScript errors are handled as exceptions that immediately generate and throw an error using the standard JavaScriptthrow mechanism. These are handled using the try…catch construct provided by the JavaScript language.
throw mechanism will raise an exception that must be handled or the Node.js process will exit immediately.
With few exceptions, synchronous APIs (any blocking method that does not return a Promise nor accept a callback function, such as fs.readFileSync()) will use throw to report errors.
Asynchronous APIs
Errors that occur within asynchronous APIs may be reported in multiple ways:Promises
Some asynchronous methods return aPromise, you should always take into account that it might be rejected:
Callbacks
Most asynchronous methods that accept acallback function will accept an Error object passed as the first argument to that function. If that first argument is not null and is an instance of Error, then an error occurred that should be handled:
Event Emitters
When an asynchronous method is called on an object that is anEventEmitter, errors can be routed to that object’s 'error' event:
Class: Error
A generic JavaScriptError object that does not denote any specific circumstance of why the error occurred. Error objects capture a “stack trace” detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.
All errors generated by Node.js, including all system and JavaScript errors, will either be instances of, or inherit from, the Error class.
new Error(message[, options])
messageoptionscauseThe error that caused the newly created error.
Error object and sets the error.message property to the provided text message. If an object is passed as message, the text message is generated by calling String(message). If the cause option is provided, it is assigned to the error.cause property. The error.stack property will represent the point in the code at which new Error() was called.
Error.captureStackTrace(targetObject[, constructorOpt])
targetObjectconstructorOpt
.stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.
Error.stackTraceLimit
- Type:
Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)).
The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed.
error.cause
- Type:
error.cause property is the underlying cause of the Error. It is used when catching an error and throwing a new one with a different message or code in order to still have access to the original error.
error.code
- Type:
error.code property is a string label that identifies the kind of error. error.code is the most stable way to identify an error. It will only change between major versions of Node.js. In contrast, error.message strings may change between any versions of Node.js.
error.message
- Type:
error.message property is the string description of the error as set by calling new Error(message). The message passed to the constructor will also appear in the first line of the stack trace of the Error.
error.stack
- Type:
error.stack property is a string describing the point in the code at which the Error was instantiated.
Class: AssertionError
- Extends:
Class: assert.AssertionError.
Class: RangeError
- Extends:
RangeError instances immediately as a form of argument validation.
Class: ReferenceError
- Extends:
Class: SyntaxError
- Extends:
eval, Function, require, or vm. These errors are almost always indicative of a broken program.
Class: SystemError
- Extends:
error.address
- Type:
error.address is a string describing the address to which a network connection failed.
error.code
- Type:
error.code property is a string representing the error code.
error.dest
- Type:
error.dest is the file path destination when reporting a file system error.
error.errno
- Type:
error.errno property is a negative number which corresponds to the error code defined in libuv Error handling.
error.info
- Type:
error.info is an object with details about the error condition.
error.message
- Type:
error.message is a system-provided human-readable description of the error.
error.path
- Type:
error.path is a string containing a relevant invalid pathname.
error.port
- Type:
error.port is the network connection port that is not available.
error.syscall
- Type:
error.syscall property is a string describing the syscall that failed.
Common System Errors
This is a list of system errors commonly-encountered when writing a Node.js program:-
EACCES(Permission denied): An attempt was made to access a file in a way forbidden by its file access permissions. -
EADDRINUSE(Address already in use): An attempt to bind a server to a local address failed due to another server on the local system already occupying that address. -
ECONNREFUSED(Connection refused): No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host. -
ECONNRESET(Connection reset by peer): A connection was forcibly closed by a peer. This normally results from a loss of the connection on the remote socket due to a timeout or reboot. -
EEXIST(File exists): An existing file was the target of an operation that required that the target not exist. -
EISDIR(Is a directory): An operation expected a file, but the given pathname was a directory. -
EMFILE(Too many open files in system): Maximum number of file descriptors allowable on the system has been reached, and requests for another descriptor cannot be fulfilled until at least one has been closed. -
ENOENT(No such file or directory): Commonly raised byfsoperations to indicate that a component of the specified pathname does not exist. -
ENOTDIR(Not a directory): A component of the given pathname existed, but was not a directory as expected. -
ENOTEMPTY(Directory not empty): A directory with entries was the target of an operation that requires an empty directory. -
ENOTFOUND(DNS lookup failed): Indicates a DNS failure of eitherEAI_NODATAorEAI_NONAME. -
EPERM(Operation not permitted): An attempt was made to perform an operation that requires elevated privileges. -
EPIPE(Broken pipe): A write on a pipe, socket, or FIFO for which there is no process to read the data. -
ETIMEDOUT(Operation timed out): A connect or send request failed because the connected party did not properly respond after a period of time.
Class: TypeError
- Extends:
TypeError.
TypeError instances immediately as a form of argument validation.
OpenSSL Errors
Errors originating incrypto or tls are of class Error, and in addition to the standard .code and .message properties, may have some additional OpenSSL-specific properties.
error.opensslErrorStack
An array of errors that can give context to where in the OpenSSL library an error originates from.error.function
The OpenSSL function the error originates in.error.library
The OpenSSL library the error originates in.error.reason
A human-readable string describing the reason for the error.Node.js Error Codes
Node.js uses error codes to identify specific error conditions. These codes are stable and won’t change except between major versions. Common error codes include:ABORT_ERR- Used when an operation has been aborted (typically using anAbortController)ERR_INVALID_ARG_TYPE- Indicates that an argument of the wrong type was passedERR_INVALID_ARG_VALUE- Indicates that an invalid or unsupported value was passedERR_OUT_OF_RANGE- Indicates that a numeric value is out of the valid range