DEV Community

Skillnter
Skillnter

Posted 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! ๐Ÿš€๐Ÿ”ฅ


Top comments (0)