Error Handling in Express.js

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

Error handling is an essential part of building robust web applications. Express.js provides built-in mechanisms to handle errors gracefully.


1. Types of Errors

  1. Synchronous Errors – Errors that occur in the main execution flow.

  2. Asynchronous Errors – Errors from callbacks, promises, or async/await.

  3. 404 Not Found – Requested route does not exist.


2. Basic Error Handling

Express allows you to define an error-handling middleware with four parameters:

function errorHandler(err, req, res, next) { console.error(err.stack); res.status(500).json({ message: err.message }); } app.use(errorHandler);
  • Must be after all routes and middleware

  • err – The error object

  • req, res, next – Standard Express objects


3. Throwing Errors in Routes

Synchronous route example:

app.get('/error', (req, res, next) => { const err = new Error('Something went wrong!'); next(err); // Pass error to error-handling middleware });

Asynchronous route example (async/await):

app.get('/async-error', async (req, res, next) => { try { await someAsyncFunction(); res.send('Success'); } catch (err) { next(err); // Forward error } });

4. Handling 404 Errors

For undefined routes:

app.use((req, res, next) => { res.status(404).json({ message: 'Route not found' }); });
  • Place before general error-handling middleware

  • Ensures all unmatched routes return a proper 404 response


5. Centralized Error Handling

Example:

// Route app.get('/user/:id', (req, res, next) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return next(new Error('User not found')); res.json(user); }); // Error-handling middleware app.use((err, req, res, next) => { res.status(err.status || 500).json({ message: err.message || 'Internal Server Error' }); });
  • Keeps error handling consistent across all routes


6. Best Practices

  1. Use centralized error-handling middleware.

  2. Do not expose stack traces in production.

  3. Use custom error classes for better error management.

  4. Handle asynchronous errors using try/catch or promise .catch().

  5. Return appropriate HTTP status codes (400, 401, 403, 404, 500).


7. Custom Error Class Example

class AppError extends Error { constructor(message, statusCode) { super(message); this.statusCode = statusCode; } } // Usage app.get('/custom-error', (req, res, next) => { next(new AppError('Custom error occurred', 400)); });
  • Makes it easier to differentiate error types and handle accordingly


Error handling in Express.js ensures your app is robust, maintainable, and secure, providing clear feedback to clients while protecting the server.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes