Throwing Errors in Node.js
This article will explain how to throw errors in Node.js.
Throwing Errors in Node.js
Errors are statements that do not allow the system to function properly.
Errors in Node.Js are handled through exceptions, which are created with the help of throw keyword. This helps the user to create custom exceptions.
Once this line of JavaScript code is executed, the normal flow of the program stops and control is passed to the nearest exception handler. If there is no catch block between the calling functions, the program terminates.
grammar:
throw expression;
The value can normally be any JavaScript value in the client code, including a number, an object, or a string. But in Node.js, we don't throw strings; we only throw error objects.
Error object
An Error object is an object which is an instance of the Error object or extends the Error class provided in the main error module. An Error object is generated when a runtime error occurs.
We can also use the error object as the base object for custom exceptions.
throw new Error('You reached the end!');
class MyCustomError extends Error {
// ...
}
throw new MyCustomError();
Handling Exceptions
Exception handlers are try...catch
statements. Any exception thrown in the lines of code contained in the try block is handled in the appropriate catch block.
If an uncaught exception is thrown while our program is running, the program will fail.
try {
/* Your Regular Code */
} catch (e) {
/* Catch your exception here */
}
e is the outlier in this case. We can add multiple handlers that can detect different types of errors.
We can then modify your program based on the exception type. To fix the program failure, wait for the event on the process object uncaughtException
.
process.on('uncaughtException', err => {
console.error('An uncaught error is caught here', err);
process.exit(1);
});
We don't need to import the main process module for this as it will be included automatically.
Handling exceptions with promises
Promises allow you to chain unique operations together and handle errors at the end. Promise chains are great for handling errors.
When a promise is rejected, control jumps to the nearest rejection handler. This is very convenient in practice.
As you can see, .catch
it is not necessarily instantaneous. It may appear .then
after one or many.
fooFunction()
.then(barFunction)
.then(fooBarFunction)
.catch(err => console.error(err));
Handling exceptions with async/await
To use async/await
, you need to use try...catch
to catch errors.
async function fooFunction() {
try {
await fooBarFunction();
} catch (err) {
console.error(err.message);
}
}
Let us understand it with the following simple example:
fooBarFunction = async() => {
throw new Error("Hello jiyii.com Users!")
}
async function fooFunction() {
try {
console.log("Before Error")
await fooBarFunction();
} catch (err) {
console.error(err.message);
}
}
fooFunction()
In the above example, we call fooFunction()
, which first prints the message and then calls internally fooBarFunction()
. In fooBarFunction()
, we simply throw an fooFunction()
error which is caught by .
Try running the above code snippet in Replit with Node.js support. It will display the following result:
The output is as follows:
Before Error
Hello jiyii.com Users!
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Solve the Cannot Find Module error in Node.js
Publish Date:2025/04/17 Views:70 Category:Node.js
-
In this article, we will learn how to fix the Cannot find module error in Node.js. package.json File Before diving into the solution, we will first try to understand the package.json file and why we need it. The package.json file is the roo