UNPKG

express-error-catcher

Version:
190 lines (138 loc) 6.6 kB
# `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: ```bash 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. ```js 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. ```js const app = express(); app.use(error({ defaultErrorMessage: "Internal server error", // Sets a default error message for uncaught errors. defaultStatusCode: 500, // Defines the default HTTP status code for errors. log: "dev" // Chooses the logging format: "dev" for detailed logs, "prod" for concise logs. })); ``` ### 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. ```js app.get( "/name", asyncErrorHandler((req, res) => { // Intentionally throwing an error throw Error("Error while retrieving name", 500); // Returning a successful response return Response("Successfully retrieved name", { name: "Daisy" }, 200); }) ); ``` ### Step 4: Start the Express Server Finally, start your Express server as usual: ```js 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: ```plaintext <-------------------------------> 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: ```plaintext ┌─────────┬─────────────────────────┬────────────────────────────────┐ │ (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: ```plaintext <-------------------------------> 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. ```js throw Error("Custom error message", 400); ``` ### Response Format #### Success Response When an operation completes successfully, the response is structured as follows: ```js return new Response("Success.", { data: "Welcome daisy.." }, 200); ``` The corresponding JSON output will be: ```json { "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: ```js throw new Error("Daisy already exists.", 400); ``` The corresponding JSON output will be: ```json { "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: ```js throw new Error("Daisy already exists.", 400, { details: "Validation failed" }); ``` ```json { "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.