Error Handling in Node.js

📘 Node.js 👁 55 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Error handling is the process of detecting, managing, and responding to runtime problems so an application can fail safely instead of crashing.
In Node.js, proper error handling is essential because the system is asynchronous and event-driven.


1. Types of Errors in Node.js

1.1 Operational Errors

Errors caused by external factors:

  • File not found

  • Network failure

  • Invalid user input

  • Database connection issues

✔ Should be handled gracefully


1.2 Programmer Errors

Errors caused by bugs in code:

  • Undefined variables

  • Logic errors

  • Type errors

❌ Should be fixed during development


2. Error Handling in Synchronous Code

Use try...catch blocks.

try { const data = JSON.parse('invalid json'); } catch (err) { console.error('Error:', err.message); }

3. Error Handling in Asynchronous Code

3.1 Callback-Based Errors

Node.js uses error-first callbacks.

fs.readFile('file.txt', (err, data) => { if (err) { console.error(err.message); return; } console.log(data); });

3.2 Promise-Based Errors

Use .catch().

fetchData() .then(result => console.log(result)) .catch(err => console.error(err));

3.3 Async/Await Errors

Use try...catch.

async function loadData() { try { const data = await fetchData(); console.log(data); } catch (err) { console.error(err.message); } }

4. Custom Errors

class AppError extends Error { constructor(message) { super(message); this.name = 'AppError'; } } throw new AppError('Something went wrong');

5. Error Handling in Express.js

5.1 Route-Level Error

app.get('/error', (req, res) => { throw new Error('Route error'); });

5.2 Error-Handling Middleware

app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });

⚠ Must be defined after routes.


6. Handling Uncaught Errors

6.1 Uncaught Exceptions

process.on('uncaughtException', err => { console.error('Uncaught Exception:', err); });

6.2 Unhandled Promise Rejections

process.on('unhandledRejection', reason => { console.error('Unhandled Rejection:', reason); });

7. Logging Errors

  • Log errors for debugging

  • Use logging libraries like winston or pino

  • Avoid exposing internal errors to users


8. Best Practices

  • Always handle async errors

  • Use centralized error handling

  • Provide meaningful error messages

  • Avoid crashing the event loop

  • Separate operational and programmer errors


9. Common Mistakes

❌ Ignoring async errors
❌ Sending stack traces to clients
❌ Catching errors and doing nothing


10. Summary

  • Error handling prevents application crashes

  • Different techniques for sync and async code

  • Express uses error-handling middleware

  • Proper logging and handling improve reliability


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes