express-error-catcher
express-error-catcher
is a robust npm package engineered to streamline error handling in Node.js Express applications. It provides an elegant solution for managing async/await errors, reducing boilerplate code, and enhancing the maintainability of your applications.
Key Features
- Automated Error Handling: Effortlessly catch and handle errors in asynchronous route handlers, allowing for cleaner and more concise code.
- Customizable Middleware: Easily configure default error messages, status codes, and logging preferences to suit your development and production environments.
- Multiple Logging Formats: Choose between detailed development logs and minimal production logs to meet your specific needs.
- Improved Code Readability: Eliminate redundant try-catch blocks, making your codebase more readable and easier to maintain.
Installation
Integrating express-error-catcher
into your project is straightforward. Use the following npm command to install the package:
npm install express-error-catcher
Usage Overview
To leverage express-error-catcher
in your Express application, follow these steps:
Step 1: Import the Package
Begin by importing the necessary functions and middleware from the express-error-catcher
package.
import express from "express";
import { asyncErrorHandler, error, Response, Error } from "express-error-catcher";
Step 2: Configure Error Handling Middleware
Apply the error-handling middleware with optional configuration parameters to customize its behavior.
const app = express();
app.use(error({
defaultErrorMessage: "Internal server error",
defaultStatusCode: 500,
log: "dev"
}));
Step 3: Define Route Handlers
Use the asyncErrorHandler
function to wrap your asynchronous route handlers. This ensures that any errors are automatically caught and passed to the error-handling middleware.
app.get(
"/name",
asyncErrorHandler((req, res) => {
throw Error("Error while retrieving name", 500);
return Response("Successfully retrieved name", { name: "Daisy" }, 200);
})
);
Step 4: Start the Express Server
Finally, start your Express server as usual:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Detailed Configuration Options
The error
middleware provides a range of configuration options to tailor error handling to your application’s requirements.
defaultErrorMessage
: A string specifying the default message to return when an error is unhandled.defaultStatusCode
: An integer representing the default HTTP status code to use when responding to unhandled errors.log
: A string determining the log format. Options include:
"dev"
: Detailed log output for development, including error messages and file paths."pretty"
: A more readable format compared to dev, with enhanced formatting for better human readability. Example."production"
: Simplified log output for production environments, focusing on error messages only.
Logging Formats
Development (dev
)
In development mode, express-error-catcher
provides detailed logs that include the error message, file path, and line number, presented in a table format for easy reading:
<------------------------------->
ERROR => Internal Server Error
FILE => /path/to/file.js:16:11
<------------------------------->
Pretty (pretty
)
In development mode, express-error-catcher offers detailed logs in a table format that includes the error message and file path. This format enhances readability and helps quickly identify issues:
┌─────────┬─────────────────────────┬────────────────────────────────┐
│ (index) │ Message │ File │
├─────────┼─────────────────────────┼────────────────────────────────┤
│ 0 │ 'Internal Server Error' │ '/path/to/file.js:16:11' │
└─────────┴─────────────────────────┴────────────────────────────────┘
Production (production
)
In production mode, logs are minimized to reduce noise and focus on essential information:
<------------------------------->
ERROR => Internal Server Error
<------------------------------->
Advanced Use Cases
Handling Custom Errors
express-error-catcher
allows you to define and handle custom errors with specific messages and status codes, providing fine-grained control over error management.
throw Error("Custom error message", 400);
Response Format
Success Response
When an operation completes successfully, the response is structured as follows:
return new Response("Success.", { data: "Welcome daisy.." }, 200);
The corresponding JSON output will be:
{
"code": 200,
"success": true,
"status": "OK",
"message": "Success.",
"data": "Welcome daisy.."
}
Error Response
If an error occurs during processing, an error is thrown with the following structure:
throw new Error("Daisy already exists.", 400);
The corresponding JSON output will be:
{
"success": false,
"code": 400,
"status": "Bad Request",
"message": "Daisy already exists."
}
Error Response with Additional Data
You can also include additional data in the error response for more context:
throw new Error("Daisy already exists.", 400, { details: "Validation failed" });
{
"success": false,
"code": 400,
"status": "Bad Request",
"message": "Daisy already exists.",
"data": {
"details": "Validation failed"
}
}
Integrating with Other Middleware
The package is designed to integrate seamlessly with other Express middleware, allowing you to create a cohesive error-handling strategy across your application.