How to handle errors in node.js ? - GeeksforGeeks (2024)

Last Updated : 01 May, 2023

Summarize

Comments

Improve

Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior may vary, unlike synchronous functions. While try-catch blocks are effective for synchronous functions, asynchronous functions can be dealt with callbacks, promises, and async-await. Try-catch is synchronous means that if an asynchronous function throws an error in a synchronous try/catch block, no error throws. Errors thrown in Node.js applications can be handled in the following ways:

  • Using try-catch block
  • Using callbacks
  • Using promises and promise callbacks
  • Using async-await

Using try-catch block: The try-catch block can be used to handle errors thrown by a block of code.

javascript

function dosomething() {

throw new Error(

'a error is thrown from dosomething');

}

function init() {

try {

dosomething();

}

catch (e) {

console.log(e);

}

console.log(

"After successful error handling");

}

init();

Output:

Error: a error is thrown from dosomething at dosomething (/home/cg/root/6422736/main.js:4:11) at init (/home/cg/root/6422736/main.js:9:9) at Object. (/home/cg/root/6422736/main.js:17:1) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:389:7)After successful error handling

Explanation: The init() function is called which in turn calls dosomething() function which throws an error object. This error object is caught by the catch block of the init() method. If there is no proper handling of the error the program will terminate. The catch block prints the call stack to show the point where the error occurred.

Using callbacks: A callback is a function called at the completion of a certain task. Callbacks are widely used in Node.js as it prevents any blocking and allows other code to be run in the meantime. The program does not wait for the file reading to complete and proceeds to print “Program Ended” while continuing to read the file. If any error occurs like the file does not exist in the system then the error is printed after “Program Ended”, else the content of the file is outputted.

javascript

const fs = require("fs");

fs.readFile('foo.txt', function (err, data) {

if (err) {

console.error(err);

}

else {

console.log(data.toString());

}

});

console.log("Program Ended");

Output:

Program Ended[Error: ENOENT: no such file or directory, open 'C:\Users\User\Desktop\foo.txt'] { errno: -4058, code: 'ENOENT', syscall: 'open', path: 'C:\\Users\\User\\Desktop\\foo.txt'}

Explanation: In this case, the file does not exist in the system hence the error is thrown. Using promises and promise callbacks: Promises are an enhancement to Node.js callbacks. When defining the callback, the value which is returned is called a “promise”. The key difference between a promise and a callback is the return value. There is no concept of a return value in callbacks. The return value provides more control for defining the callback function. In order to use promises, the promise module must be installed and imported into the application. The .then clause handles the output of the promise. If an error occurs in any .then clause or if any of the promises above are rejects, it is passed to the immediate .catch clause. In case of a promise is rejected, and there is no error handler then the program terminates.

javascript

const Promise = require('promise');

const MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url)

.then(function (err, db) {

db.collection('Test').updateOne({

"Name": "Joe"

},

{

$set: {

"Name": "Beck"

}

});

})

.catch(error => alert(error.message))

Output:

// In this case we assume the url is wrongMongoError: failed to connect to server [localhost:27017]// error message may vary

Using async-await: Async-await is a special syntax to work with promises in a simpler way that is easy to understand. When we use async/await, .then is replaced by await which handles the waiting in the function. The error handling is done by the .catch clause. Async-await can also be wrapped in a try-catch block for error handling. In case no error handler exists the program terminates due to an uncaught error.

javascript

async function f() {

let response = await fetch('http://xyzurl');

}

// f() becomes a rejected promise

f().catch(alert);

Output:

// the url is wrong //TypeError: failed to fetch 


S

Shreyasi_Chakraborty

How to handle errors in node.js ? - GeeksforGeeks (1)

Improve

Next Article

How to handle errors in Node JS ?

Please Login to comment...

How to handle errors in node.js ? - GeeksforGeeks (2024)
Top Articles
Understanding FOB | John Pipe International
The Best Technical Traders of All Time | MarketBulls
Dragon Age Inquisition War Table Operations and Missions Guide
Academic Integrity
Aiken County government, school officials promote penny tax in North Augusta
Bustle Daily Horoscope
What Was D-Day Weegy
Synq3 Reviews
Assets | HIVO Support
Regal Stone Pokemon Gaia
Walmart Windshield Wiper Blades
Most McDonald's by Country 2024
Craiglist Tulsa Ok
25Cc To Tbsp
De beste uitvaartdiensten die goede rituele diensten aanbieden voor de laatste rituelen
Jalapeno Grill Ponca City Menu
TBM 910 | Turboprop Aircraft - DAHER TBM 960, TBM 910
Silive Obituary
Tyler Sis University City
Red Cedar Farms Goldendoodle
Boston Dynamics’ new humanoid moves like no robot you’ve ever seen
Jeff Nippard Push Pull Program Pdf
Afni Collections
O'reilly's In Mathis Texas
Kaliii - Area Codes Lyrics
Shoe Station Store Locator
Poe T4 Aisling
Laveen Modern Dentistry And Orthodontics Laveen Village Az
Redding Activity Partners
Kempsville Recreation Center Pool Schedule
Ghid depunere declarație unică
Transformers Movie Wiki
Tire Pro Candler
Scat Ladyboy
Http://N14.Ultipro.com
Salons Open Near Me Today
Spinning Gold Showtimes Near Emagine Birch Run
Manatee County Recorder Of Deeds
7543460065
Marcus Roberts 1040 Answers
Gun Mayhem Watchdocumentaries
Sam's Club Gas Prices Florence Sc
Penny Paws San Antonio Photos
✨ Flysheet for Alpha Wall Tent, Guy Ropes, D-Ring, Metal Runner & Stakes Included for Hunting, Family Camping & Outdoor Activities (12'x14', PE) — 🛍️ The Retail Market
St Vrain Schoology
Port Huron Newspaper
Espn Top 300 Non Ppr
Mlb Hitting Streak Record Holder Crossword Clue
Twizzlers Strawberry - 6 x 70 gram | bol
Obituary Roger Schaefer Update 2020
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 6577

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.