DEV Community

Cover image for Advanced Error Handling in Node.js
Amruta
Amruta

Posted on

Advanced Error Handling in Node.js

Error handling is an important aspect of software development that ensures your application behaves predictably and provides meaningful feedback when something goes wrong. In Node.js, effective error handling can be particularly challenging due to its asynchronous nature. This article delves into advanced techniques and best practices for managing errors in Node.js applications.

Understanding Error Types

Before diving into error handling strategies, it’s important to understand the types of errors you might encounter:

  1. Synchronous Errors:
    The errors that occur during the execution of synchronous code, can be caught using try-catch blocks.

  2. Asynchronous Errors:
    The errors occur during the execution of asynchronous code, such as callbacks, promises, and async/await functions.

  3. Operational Errors:
    Errors that represent runtime problems that the program is expected to handle (e.g., failing to connect to a database).

  4. Programmer Errors:
    Bugs in the program (e.g., type errors, assertion failures). These should generally not be caught and handled in the same way as operational errors.

Synchronous Error Handling

For synchronous code, error handling is using try-catch blocks:

try {
  // Synchronous code that might throw an error
  let result = dafaultFunction();
} catch (error) {
  console.error('An error occurred:', error.message);
  // Handle the error appropriately
}
Enter fullscreen mode Exit fullscreen mode

Asynchronous Error Handling

  • Callbacks

In callback-based asynchronous code, errors are usually the first argument in the callback function:

const fs = require('fs');
fs.readFile('/path/to/file', (err, data) => {
  if (err) {
    console.error('An error occurred:', err.message);
    // Handle the error
    return;
  }
  // Process the data
});
Enter fullscreen mode Exit fullscreen mode
  • Promises

Promises offer a cleaner way to handle asynchronous errors using .catch():

const fs = require('fs').promises;
fs.readFile('/path/to/file')
  .then(data => {
    // Process the data
  })
  .catch(err => {
    console.error('An error occurred:', err.message);
    // Handle the error
  });
Enter fullscreen mode Exit fullscreen mode
  • Async/Await

Async/await syntax allows for a more synchronous style of error handling in asynchronous code:

const fs = require('fs').promises;
async function readFile() {
  try {
    const data = await fs.readFile('/path/to/file');
    // Process the data
  } catch (err) {
    console.error('An error occurred:', err.message);
    // Handle the error
  }
}
readFile();
Enter fullscreen mode Exit fullscreen mode

Centralized Error Handling

For larger applications, centralized error handling can help manage errors more effectively. This often involves middleware in Express.js applications.

  • Express.js Middleware

Express.js provides a mechanism for handling errors via middleware. This middleware should be the last in the stack:

const express = require('express');
const app = express();

// Define routes and other middleware
app.get('/', (req, res) => {
  throw new Error('Something went wrong!');
});

// Error-handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Internal Server Error' });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

Advanced Techniques

  • Custom Error Classes

Creating custom error classes can help distinguish between different types of errors and make error handling more granular:

class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    Error.captureStackTrace(this, this.constructor);
  }
}

// Usage
try {
  throw new AppError('Custom error message', 400);
} catch (error) {
  if (error instanceof AppError) {
    console.error(`AppError: ${error.message} (status: ${error.statusCode})`);
  } else {
    console.error('An unexpected error occurred:', error);
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Error Logging

Implement robust error logging to monitor and diagnose issues. Tools like Winston or Bunyan can help with logging:

const winston = require('winston');
const logger = winston.createLogger({
  level: 'error',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log' })
  ]
});

// Usage
try {
  // Code that might throw an error
  throw new Error('Something went wrong');
} catch (error) {
  logger.error(error.message, { stack: error.stack });
}
Enter fullscreen mode Exit fullscreen mode
  • Global Error Handling

Handling uncaught exceptions and unhandled promise rejections ensures that no errors slip through unnoticed:

process.on('uncaughtException', (error) => {
  console.error('Uncaught Exception:', error);
  // Perform cleanup and exit process if necessary
});
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // Perform cleanup and exit process if necessary
});
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Fail Fast: Detect and handle errors as early as possible.

  • Graceful Shutdown: Ensure your application can shut down gracefully in the event of a critical error.

  • Meaningful Error Messages: Provide clear and actionable error messages.

  • Avoid Silent Failures: Always log or handle errors to avoid silent failures.

  • Test Error Scenarios: Write tests to cover potential error scenarios and ensure your error handling works as expected.

Conclusion

To effectively handle errors in Node.js, you need to use a combination of synchronous and asynchronous techniques, centralized management, and advanced strategies such as custom error classes and robust logging. By incorporating these best practices and advanced techniques, you can create robust Node.js applications that gracefully handle errors and offer an improved experience for your users.

Top comments (18)

Collapse
 
litlyx profile image
Antonio | CEO at Litlyx.com

Really good article! We have created this open-source project, where you can track anything in your web-app or website. You can customize your events too, and can be used even in production with 'Error Events' so you can always check where the exception are even in production!

The project is open-source on Github.

Antonio, CEO & Founder at Litlyx.com

Collapse
 
rkristelijn profile image
Remi Kristelijn

Great article! I want to point out that extensive logging, especially when explicitly writing to a file can result a performance issue. Therefore you could just log to the console and let e.g. kubernetes handle the logging. Also central logging is important, e.g. use of open search and e.g. npmjs.com/package/console-log-json

Collapse
 
learn_with_santosh profile image
Santosh Shelar

Great advice! These best practices ensure your applications can gracefully handle errors and provide a better user experience.

Collapse
 
mehedihasan2810 profile image
Mehedi Hasan

Good read

Collapse
 
devpaul3000 profile image
Dev Paul

Great article. Creating custom error classes is a really powerful approach that make error handling a easy and sometimes fun

Collapse
 
the_riz profile image
Rich Winter • Edited

Good stuff.
Don't forget that Promises both resolve and reject

Collapse
 
amritak27 profile image
Amruta

You're right, Promises can resolve and reject, and it's important to handle both cases

Collapse
 
syedmuhammadaliraza profile image
Syed Muhammad Ali Raza

nice

Collapse
 
mrrishimeena profile image
Rishi Kumar

True, Error handling is the first part towards debugging the issues in Node.js . Its the first step towards knowing the root cause of the error. There are many more steps afterwards to find and verify the fix of the issues. But its takes hours. Thats why we build the errsole which can helps the developers to fix the errors in minutes.

Collapse
 
mrrishimeena profile image
Rishi Kumar

Check out opensource library GitHub errsole.js , Its the first in world opensource 'logging library' which has built-in dashboard. Its much better than winston, pino and even paid cloudwatch.

Collapse
 
leo_jackson_e6f81956bd52b profile image
Leo Jackson

I had my funds stolen from Coinbase .. I don’t know how the hacking was done but all of my funds disappeared after I sent $215 as fee to claim an airdrop on ETH.. this airdrop supposedly came as a result of following the token launch and as a result of being amongst the early holders, we were supposed to claim a free token in total sum of $82,000 per person once launched but we were required to pay gas fees to claim it so I paid mine to the wallet they gave to me and next thing I knew, all the funds in my wallet worth $312,621 USD disappeared, I was confused , no idea what just happened so I started asking questions which led me to Bitquery Retriever Hacker, and I got to find out that by sending gas fee to the wallet I enabled them to hack into my coinbase account, the wallet address they gave contained some virus which i had no idea about, Bitquery Retriever Hacker explained everything to me and it opened my eyes as well but they also assured me the full recovery of my money, I trusted and believed Bitquery Retriever Hacker, but the only thing that diluted my pain and anxiety was when I saw my funds all available in my Coinbase wallet on the 3rd day of taking on my case, I looked and it was all there and for the first time since the incident , I felt Alive and all thanks to the Bitquery Retriever Hacker, from the funds I also paid for the service with a little bonus cos am grateful, but in the beginning i only paid for the tools required for the recovery of my funds.
To contact Bitquery Retriever Hacker you can reach out to them Telegram: @Bitqueryretrieverhacker
And Email: bitqueryretrieverhacker@bitquery.c...

Collapse
 
graham_smith_8a090f5b5336 profile image
Graham Smith

RELIEF FOR CRYPTO SCAM VICTIMS; FUNDS RETRIEVED BY GRAYHATHACKS CONTRACTOR

I am thrilled to share my experience with Grayhathacks Contractor, as I never thought I would be one of those people writing a positive review for an online service. I was fully prepared to rant about being scammed further, but luckily I stumbled upon an honest team of hackers who are out to help.

After falling victim to a well-executed investment scam that cost me nearly a quarter of a million dollars, I decided to take a chance on Grayhathacks Contractor. And boy, did they deliver!

Specializing in crypto recovery, Grayhathacks Contractor is a team of expert professionals dedicated to helping individuals and businesses reclaim their lost funds from investment scams. With their impressive track record and top-notch customer service, I was hopeful that I was in good hands.

I was not disappointed. Thanks to their efforts, we were able to track down the scammers and recover the full amount I had lost and all within a short period of a week. I couldn't believe it either once I saw the funds back in my wallet, I thought it was a trick. Imagine how happy I felt after I verified that indeed I got my funds back.

I cannot thank Grayhathacks enough for their exceptional service. They truly are the best in the business when it comes to crypto tracking and recovery. If you ever find yourself in a similar situation, do not hesitate to reach out to them using the contact information provided below.

WhatsApp: +1 (843) 368-3015
Email:
grayhathacks@contractor.net
Image description

Collapse
 
michael_marie_4d05a1b8e6b profile image
Info Comment hidden by post author - thread only accessible via permalink
Michael Marie

Cyberspace Hack Pro came to my rescue when I was at my lowest, having fallen victim to a deceitful Forex Investment Company. The loss of my hard-earned funds left me feeling defeated and unsure of where to turn. However, upon discovering Cyberspace Hack Pro, I found renewed hope and determination.They immediately apparent. Their team of experts and hackers demonstrated unparalleled skill and dedication in their mission to help me. They left no stone unturned, tirelessly pursuing justice on my behalf. Their commitment to aiding individuals like myself in navigating the treacherous world of online fraud was truly commendable.But what truly sets Cyberspace Hack Pro apart is their unwavering determination to deliver results. Through their relentless efforts, they managed to track and recover the entirety of my lost funds, totaling an impressive 4.26476 BTC. This achievement not only lifted a huge weight off my shoulders but also restored my faith in the possibility of justice prevailing, even in the digital realm.the recovery process, Cyberspace Hack Pro provided unwavering support and guidance. They kept me informed every step of the way, offering reassurance and direction during what was undoubtedly a challenging time. Their professionalism and empathy served as a beacon of hope, reminding me that I was not alone in my quest for restitution.Looking back on my experience, I am filled with gratitude for having found Cyberspace Hack Pro. Their expertise and dedication turned what initially seemed like an insurmountable obstacle into a triumph of justice. Recovering my lost funds through their assistance stands as one of the best decisions I made this year, a testament to their efficacy and reliability.For anyone facing a similar situation, I wholeheartedly recommend reaching out to Cyberspace Hack Pro. Their proven track record and unwavering commitment to client satisfaction make them the go-to choice for recovering lost funds from online scams. With Cyberspace Hack Pro by your side, you can rest assured that you are in capable hands, guided by professionals who prioritize your interests above all else. Cyberspace Hack Pro exceeded all my expectations, delivering results that surpassed my wildest dreams. Their professionalism, expertise, and unwavering dedication to client satisfaction set them apart as industry leaders in the realm of fund recovery. Trusting Cyberspace Hack Pro was undoubtedly one of the best decisions I made this year, and I am forever grateful for their assistance in reclaiming my digital assets into my account.

WhatsApp:  +1 (440) 7423096

E-MAIL; Cyberspacehackpro(@)rescueteam. com

cyberspacehackpro0.wixsite.com/cyb...

Uploading image

Collapse
 
jackson_brown_c38e04bcf2a profile image
Jackson Brown

I've been in the real estate business for over 20 years and I was always on the lookout for new lucrative investments. Bitcoin caught my eye early on, and I decided to invest $10,000 in purchasing Bitcoin. Over time, my investment shot to $600,000. This significant profit margin allowed me to expand my real estate business and purchase additional properties. However, my joy turned to panic when I received an email that seemed to be from my trading platform. It asked me to verify my account details. Without hesitation, I provided the information. Soon after, I discovered that my Bitcoin wallet had been drained. Devastated, I sought help and found a recommendation for Dumbledore web expert Recovery on a real estate forum. I contacted them immediately, hoping they could assist me. Their team was highly professional and quick in their response. They meticulously traced the fraudulent activity and managed to recover most of my funds. Dumbledore web expert also educated me on crucial security measures. They emphasized the importance of using two-factor authentication, creating strong, unique passwords, and recognizing phishing attempts. This experience was a tough lesson, but their guidance helped me secure my Bitcoin more effectively for the future. I will advise everyone to contact Dumbledore web expert if your bitcoin was stolen or you being scammed through their contact info below :

Email: dumbledorewebexpert(@)usa.com
WhatsApp: +1-(231)-425-0878

Collapse
 
jackson_brown_c38e04bcf2a profile image
Jackson Brown

I've been in the real estate business for over 20 years and I was always on the lookout for new lucrative investments. Bitcoin caught my eye early on, and I decided to invest $10,000 in purchasing Bitcoin. Over time, my investment shot to $600,000. This significant profit margin allowed me to expand my real estate business and purchase additional properties. However, my joy turned to panic when I received an email that seemed to be from my trading platform. It asked me to verify my account details. Without hesitation, I provided the information. Soon after, I discovered that my Bitcoin wallet had been drained. Devastated, I sought help and found a recommendation for Dumbledore web expert Recovery on a real estate forum. I contacted them immediately, hoping they could assist me. Their team was highly professional and quick in their response. They meticulously traced the fraudulent activity and managed to recover most of my funds. Dumbledore web expert also educated me on crucial security measures. They emphasized the importance of using two-factor authentication, creating strong, unique passwords, and recognizing phishing attempts. This experience was a tough lesson, but their guidance helped me secure my Bitcoin more effectively for the future. I will advise everyone to contact Dumbledore web expert if your bitcoin was stolen or you being scammed through their contact info below :

Email: dumbledorewebexpert(@)usa.com
WhatsApp: +1-(231)-425-0878

Collapse
 
leo_jackson_e6f81956bd52b profile image
Leo Jackson

I had my funds stolen from Coinbase .. I don’t know how the hacking was done but all of my funds disappeared after I sent $215 as fee to claim an airdrop on ETH.. this airdrop supposedly came as a result of following the token launch and as a result of being amongst the early holders, we were supposed to claim a free token in total sum of $82,000 per person once launched but we were required to pay gas fees to claim it so I paid mine to the wallet they gave to me and next thing I knew, all the funds in my wallet worth $312,621 USD disappeared, I was confused , no idea what just happened so I started asking questions which led me to Bitquery Retriever Hacker, and I got to find out that by sending gas fee to the wallet I enabled them to hack into my coinbase account, the wallet address they gave contained some virus which i had no idea about, Bitquery Retriever Hacker explained everything to me and it opened my eyes as well but they also assured me the full recovery of my money, I trusted and believed Bitquery Retriever Hacker, but the only thing that diluted my pain and anxiety was when I saw my funds all available in my Coinbase wallet on the 3rd day of taking on my case, I looked and it was all there and for the first time since the incident , I felt Alive and all thanks to the Bitquery Retriever Hacker, from the funds I also paid for the service with a little bonus cos am grateful, but in the beginning i only paid for the tools required for the recovery of my funds. To contact Bitquery Retriever Hacker you can reach out to them on WhatsApp: +1 (202) (773- 9556) Telegram: @Bitqueryretrieverhacker Or Email: ( bitqueryretrieverhacker @bitquery .co .site )

Collapse
 
fortune_coder profile image
Shedrack Davis

I love it. Thanks for sharing.

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more