DEV Community

Skillnter
Skillnter

Posted on β€’ Edited on

πŸš€ "Oops! Something Went Wrong" – Handling API Errors in Express.js Like a Pro

πŸ’‘ "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! πŸš€πŸ”₯


Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay