Node.js inherits the JavaScript and system errors from the JavaScript <Error> class and it guarantees to provide the properties which are available on that class. The JavaScript exceptions that immediately throws errors using the throw mechanism that are handled by try…catch construct that is provided by the JavaScript.
Node.js handles errors that occur during the application running, supports multiple error mechanisms i.e. how all these errors are reported and handled depends on Error type and API style. Application code can trigger user-specified errors also. All those errors that are generated by the Node.js are either the instances or inherited from the Error class. In Node.js, it experiences many types of errors while running applications that are given below:
Class: AssertionError: AssertionErrors are Extended by the <errors.Error> Class. When it detects that an exceptional logic violation has occurred that should never occur, then these errors are triggered and the assert module raises all these errors. All those errors that are thrown by the assert module are instances of AssertionError class.
Example 1: Filename: index.js
const assert = require( 'assert' );
console.log( "Throws Assertion Error..." );
assert.strictEqual(
{ 'Alfa' : 'hi' , 'beta' : 'hello' },
{ 'Alfa' : 'hi' , 'beta' : 'hello' }
);
|
Run index.js file using the following command:
node index.js
Output:
Throws Assertion Error
>> Throws Assertion Error…
>> assert.js:101
throw new AssertionError(obj);
AssertionError [ERR_ASSERTION]: Values have same structure but are not reference-equal:
{ Alfa: ‘hi’, beta: ‘hello’} at Object.<anonymous> (C:\Users\Ajay Kumar\Desktop\test2.js:12:8)……. operator: ?[32m’strictEqual’?[39m}
Class: RangeError: It shows that the provided argument was not within the acceptable range of values. It could be a numeric range, or outside the set of options.
Example 2: Filename: index.js
const http = require( 'http' );
var server = http.createServer()
.listen(46456656, (err, res)=>{
});
|
Output:
Throws Range Error
>> internal/validators.js:192
throw new ERR_SOCKET_BAD_PORT(name, port);
RangeError [ERR_SOCKET_BAD_PORT]: options.port should be >= 0 and < 65536. Received 46456656……. code: ?[32m’ERR_SOCKET_BAD_PORT’?[39m}
Class: ReferenceError: It specifies that the variable anyone is trying to access is not defined. Such types of errors specify typos in code or a broken program. The instances of ReferenceError specify a bug in the code until an application is dynamically running code.
Example 3: Filename: index.js
try {
const alfa = 10;
const beta = alfa + gamma;
} catch (err) {
console.log(err.message);
console.log(err);
}
|
Output:
Throws Reference Error
>> gamma is not defined
>> ReferenceError: gamma is not defined
at Object.<anonymous> (C:\Users\Ajay Kumar\Desktop\test2.js:128:23)……at internal/main/run_main_module.js:17:47
Class: SyntaxError: It specifies that the program is not a valid JavaScript and it may be generated as a result of code evaluation. These errors mostly happen as a result of eval, Function, require, or vm.
Example 4: Filename: index.js
try {
require( 'vm' ).runInThisContext( 'alfa @ beta' );
} catch (error) {
console.log(error);
}
|
Output:
Throws Syntax Error
>> alfa @ beta
>> SyntaxError: Invalid or unexpected token
at new Script (vm.js:99:7)……at internal/main/run_main_module.js:17:47
Class: SystemError: System errors that are generated by Node.js occur due to exceptions within its runtime environment. when an application violates an operating system constraint then these errors could be expected.
Example 5: Filename: index.js
const fs = require( 'fs' );
function errorCallback(err, data) {
if (err) {
console.error( 'There was an error' , err);
return ;
}
return (data);
}
fs.readFile( '/some/non-existing/file' , errorCallback);
|
Output:
Throws Error
>> There was an error [Error: ENOENT: no such file or directory, open ‘C:\some\non-existing\file’] {
errno: -4058,
code: ‘ENOENT’,
syscall: ‘open’,
path: ‘C:\\some\\non-existing\\file’}
Class: TypeError: It specifies that the argument provided is not an allowable type. For example, calling a function that actually doesn’t exist would be a TypeError. As if the form is of argument validation, it throws TypeError instances immediately.
Example 6: Filename: index.js
try {
if (1) {
if (2) {
console.loo( 'alfa' )
}
}
} catch (error) {
console.log(error);
}
|
Run index.js file using the following command:
node index.js
Output:
Throws Type Error
>> TypeError: console.loo is not a function
at Object.<anonymous> (C:\Users\Ajay Kumar\Desktop\test2.js:104:15)……at internal/main/run_main_module.js:17:47
Reference: https://nodejs.org/api/errors.html#errors_class_assertionerror
Similar Reads
Node.js console.error() Function
The console.error() function from the console class of Node.js is used to display an error message on the console. It prints to stderr with a newline. Syntax: console.error([data][, ...args]) Parameter: This function can contain multiple parameters. The first parameter is used for the primary messag
1 min read
Error-First Callback in Node.js
Error-First Callback in Node.js is a function which either returns an error object or any successful data returned by the function. The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first ar
2 min read
Node.js assert.ifError() Function
The assert module provides a set of assertion functions for verifying invariants. The assert.ifError() function throws value if value is not undefined or null. When testing the error argument in callbacks, this function is very useful. Syntax:Â Â assert.ifError(value)Â value: This parameter holds the a
2 min read
Import and Export in Node.js
Importing and exporting files are important parts of any programming language. Importing functions or modules enhances the reusability of code. When the application grows in size, maintaining a single file with all the functions and logic becomes difficult. It also hinders the process of debugging.
3 min read
Node.js assert.equal() Function
The assert module provides a set of assertion functions for verifying invariants. The assert.equal() function tests for equality between the actual and the expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.equal(actual, expe
2 min read
How to use Class in Node ?
In Node, classes function as templates for creating objects in object-oriented programming, encapsulating both data and behavior. They provide a structured and reusable approach to defining and instantiating objects within a JavaScript program. We will discuss the following two approaches to define
3 min read
What is an error-first callback in Node.js ?
In this article, we are going to explore the Error-first callback in Node.js and its uses. Error-first callback in Node.js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This er
2 min read
Node.js assert.doesNotMatch() Function
The assert module provides a set of assertion functions for verifying invariants. The assert.doesNotMatch() function expects the string input not to match the regular expression. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.doesNotMatch(str
2 min read
Node.js assert.match() Function
The assert module provides a set of assertion functions for verifying invariants. The assert.match() function expects the string input to match the regular expression. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.match(string, regexp[, mess
2 min read
Node.js assert.deepEqual() Function
The assert module provides a set of assertion functions for verifying invariants. The assert.deepEqual() function tests deep equality between the actual and the expected parameters. If the condition is true it will not produce an output else an assertion error is raised. Syntax: assert.deepEqual(act
2 min read