-
-
Notifications
You must be signed in to change notification settings - Fork 0
How to Handle API Errors in Express.js Like a Pro
Himanshu Bansal edited this page Feb 23, 2025
·
2 revisions
Effective error handling in Express.js is crucial for building robust applications. The http-error-kit package offers a structured approach to managing HTTP errors, including the ability to set a global error formatter for consistent error responses.
Developers often handle errors in an ad-hoc manner, leading to:
- Manual Status Codes: Manually setting status codes can introduce errors.
- Inconsistent Responses: Different routes may return errors in varying formats.
- Lack of Metadata: Essential debugging information might be missing.
http-error-kit provides predefined HTTP error classes and allows for a global error formatter to standardize error responses across your application.
npm install http-error-kit- Set Up the Global Formatter: Define a formatter function that specifies the structure of your error responses.
-
Configure the Formatter: Apply this formatter globally using
KitHttpErrorConfig. -
Use Predefined Error Classes: Replace manual error handling with
http-error-kit's error classes. - Centralized Error Handling Middleware: Ensure all errors are processed through a single middleware.
Here's how you can implement this:
const express = require('express');
const { NotFoundError, KitHttpErrorConfig } = require('http-error-kit');
const app = express();
// Define a global formatter
KitHttpErrorConfig.configureFormatter((statusCode, message, details) => ({
status: statusCode,
error: message,
info: details,
timestamp: new Date().toISOString(),
}));
// Sample route
app.get('/example', (req, res, next) => {
try {
// Simulate an error
throw new NotFoundError('Resource not found', { resource: 'example' });
} catch (error) {
next(error);
}
});
// Centralized Error Response Middleware (Minimal & Correct)
app.use((err, req, res, next) => {
res.status(err.status || err.statusCode || 500).json(err);
});
app.listen(3000, () => console.log('Server running on port 3000'));-
Global Formatter: By configuring a global formatter, all instances of
KitHttpErrorwill adhere to the defined structure, ensuring consistency. -
Minimal Centralized Error Handling Middleware: Since errors are already formatted by
http-error-kit, we simply return the error instance. No extra processing is needed.
- Consistency: Uniform error responses across all routes.
- Customization: Easily adjust the global formatter to include additional fields like timestamps or trace IDs.
- Simplicity: Reduces boilerplate code by utilizing predefined error classes.
Incorporate http-error-kit into your Express.js applications to achieve efficient, consistent, and scalable error handling.