🚀 "Oops! Something Went Wrong" – Handling API Errors in Express.js Like a Pro
Codanyks

Codanyks @codanyks

About: Open-source contributor Passionate about clean, structured code. Sharing insights on Node.js, Express & API best practices—because coding shouldn’t be a nightmare! 😅 Always learning, always sharing!

Location:
Rajasthan, India
Joined:
Feb 23, 2025

🚀 "Oops! Something Went Wrong" – Handling API Errors in Express.js Like a Pro

Publish Date: Feb 23
0 0

💡 "Why is my API returning 500 Internal Server Errors everywhere?"

💡 "How do I make sure my error messages are consistent across all endpoints?"

If you've ever wrestled with these questions while working with Express.js, you're not alone! Error handling in APIs is often an afterthought, leading to inconsistent responses, poor debugging experience, and confusing API behavior.

But what if I told you there's a better way to handle API errors—one that's structured, scalable, and easy to implement? Enter http-error-kit. 🛠️


❌ The Common Pitfalls of API Error Handling

Many developers (including past me! 😅) take a manual approach to error handling in Express.js:

app.get('/example', (req, res) => {
  if (!req.query.id) {
    res.status(400).json({ error: 'Missing required parameter: id' });
  } else {
    res.json({ message: 'Success' });
  }
});
Enter fullscreen mode Exit fullscreen mode

👉 The problem? Every route reinvents the wheel for handling errors.

Now, let’s look at the chaos this causes:

🔹 Inconsistent Responses: Some routes return { error: '...' }, others { message: '...' }.

🔹 Scattered Error Handling: Every route has its own logic, leading to duplication.

🔹 Hard to Debug: Without a proper structure, debugging becomes a nightmare.


✅ The Magic Sauce: Global Error Formatting with http-error-kit

Instead of manually formatting errors in every response, http-error-kit provides a centralized error formatter. Once configured, all errors automatically follow a consistent format across your API—no extra work needed!

1️⃣ Install the Package

npm install http-error-kit
Enter fullscreen mode Exit fullscreen mode

2️⃣ Set Up a Global Error Formatter (The Real Magic Sauce!)

With http-error-kit, you don’t need to manually format each error. Instead, define a single formatter that applies to all errors in your API.

const { KitHttpErrorConfig } = require('http-error-kit');

KitHttpErrorConfig.configureFormatter((statusCode, message, details) => ({
  status: statusCode,
  error: message,
  info: details,
  timestamp: new Date().toISOString(),
}));
Enter fullscreen mode Exit fullscreen mode

💡 Why is this powerful? If you ever need to change the format, you only modify it once, and every API response updates automatically. No need to rewrite error handling in multiple places!


3️⃣ Throw Errors Instead of Manually Setting Status Codes

With http-error-kit, you can throw structured errors instead of manually setting response statuses.

const { NotFoundError } = require('http-error-kit');

app.get('/example', (req, res, next) => {
  try {
    throw new NotFoundError('Resource not found', { resource: 'example' });
  } catch (error) {
    next(error);
  }
});
Enter fullscreen mode Exit fullscreen mode

💡 No more res.status(404).json({ message: 'Not Found' })! Just throw an error, and let the system handle it.


🔥 4️⃣ Final Response Handler

Although the real power comes from KitHttpErrorConfig.configureFormatter(), you still need an Express error-handling middleware to set the status code and return the error.

app.use((err, req, res, next) => {
  res.status(err.status || err.statusCode || 500).json(err);
});
Enter fullscreen mode Exit fullscreen mode

This middleware only ensures the correct status code is set—the actual response structure is already handled by the global formatter.


🎯 Why Use http-error-kit?

💡 “Good developers write code. Great developers handle errors properly.”

Here’s why this approach is a game-changer:

🚀 Consistency – Every error follows the same format across all routes.

🚀 Readability – Code becomes easier to read and maintain.

🚀 Scalability – Works well with larger APIs and microservices.

🚀 Debugging Made Easy – Every error includes details that help you find issues faster.


🔗 Try It Out!

Want to make your Express.js error handling cleaner and more efficient?

👉 Check out the full guide here: GitHub Wiki

👉 npm package: http-error-kit

If this helped you, leave a comment or share your thoughts! 🚀


✨ Final Thoughts

Error handling is an underrated but critical part of building great APIs. With a structured approach, you can save hours of debugging time and make your APIs more developer-friendly.

Have you tried http-error-kit? Let’s discuss your experience in the comments below! 🚀🔥


Comments 0 total

    Add comment