Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

express-error-catcher

Package Overview
Dependencies
Maintainers
0
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-error-catcher - npm Package Compare versions

Comparing version 1.0.1 to 1.0.2

13

build/index.d.ts

@@ -1,6 +0,13 @@

import { Request, Response as Response$1, NextFunction } from 'express';
import { Request, Response as Response$1, NextFunction, ErrorRequestHandler } from 'express';
import * as qs from 'qs';
import * as express_serve_static_core from 'express-serve-static-core';
declare const tryCatch: (errFunction: Function) => (req: Request, res: Response$1, next: NextFunction) => Promise<void>;
declare const _default: (err: any, req: Request, res: Response$1, next: NextFunction) => void;
interface ErrorHandlerOptions {
log?: "dev" | "pretty" | "production";
defaultStatusCode?: number;
defaultErrorMessage?: string;
}
declare const errorHandler: ErrorRequestHandler<express_serve_static_core.ParamsDictionary, any, any, qs.ParsedQs, Record<string, any>> & ((options?: ErrorHandlerOptions) => ErrorRequestHandler);

@@ -20,2 +27,2 @@ declare class Response {

export { ErrorHandler as Error, Response, tryCatch as asyncErrorHandler, _default as error };
export { ErrorHandler as Error, Response, tryCatch as asyncErrorHandler, errorHandler as error };

@@ -79,3 +79,4 @@ "use strict";

// src/errorHandler.ts
// src/error.ts
var import_http_status_codes2 = require("http-status-codes");
var ErrorHandler = class extends Error {

@@ -88,39 +89,89 @@ statusCode;

this.data = data;
Error.captureStackTrace(this, this.constructor);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
};
var errorHandler_default = ErrorHandler;
// src/error.ts
var import_http_status_codes2 = require("http-status-codes");
var error_default = (err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.message = err.message || "Internal Server Error";
if (err.name === "CastError") {
const message = `Resource Not Found. Invalid: ${err.path}`;
err = new errorHandler_default(message, 400);
var logFormatter = (...prop) => {
console.log("<------------------------------->");
for (const i of prop) {
console.log(i);
}
if (err.code === 11e3) {
const message = `Duplicate ${Object.keys(err.keyValue)} entered`;
err = new errorHandler_default(message, 400);
}
if (err.code === "JsonWebTokenError") {
const message = "JWT Error";
err = new errorHandler_default(message, 400);
}
if (err.code === "JsonWebTokenError") {
const message = "JWT is Expired";
err = new errorHandler_default(message, 400);
}
const response = {
success: false,
code: err.statusCode,
status: (0, import_http_status_codes2.getReasonPhrase)(err.statusCode),
message: err.message
console.log("<------------------------------->");
};
var createErrorHandler = (options) => {
const middleware = (err, req, res, next) => {
err.statusCode = err.statusCode || options?.defaultStatusCode || 500;
err.message = err.message || options?.defaultErrorMessage || "Internal Server Error";
if (options?.log) {
const logErrorLocation = (stack) => {
if (stack) {
const stackLines = stack.split("\n");
if (stackLines.length > 1) {
const errorLocation = stackLines[1].trim();
if (options.log === "dev") {
logFormatter(`ERROR => ${err.message}`, `FILE => ${errorLocation.replace("at ", "")}`);
} else if (options.log === "pretty") {
console.table([{ Message: err.message, File: errorLocation.replace("at ", "") }]);
} else if (options.log === "production") {
logFormatter(`ERROR => ${err.message}`);
}
}
}
};
logErrorLocation(err.stack);
}
if (err.name === "CastError") {
const message = `Resource Not Found. Invalid: ${err.path}`;
err = new ErrorHandler(message, 400);
}
if (err.code === 11e3) {
const message = `Duplicate ${Object.keys(err.keyValue)} entered`;
err = new ErrorHandler(message, 400);
}
if (err.name === "JsonWebTokenError") {
const message = "JWT Error";
err = new ErrorHandler(message, 400);
}
if (err.name === "TokenExpiredError") {
const message = "JWT is Expired";
err = new ErrorHandler(message, 400);
}
const response = {
success: false,
code: err.statusCode,
status: (0, import_http_status_codes2.getReasonPhrase)(err.statusCode),
message: err.message
};
if (err.data) {
response.data = err.data;
}
res.status(err.statusCode).json(response);
};
if (err.data) {
response.data = err.data;
return middleware;
};
var errorHandler = (optionsOrErr, req, res, next) => {
let err = optionsOrErr instanceof Error;
if (err) {
const err2 = optionsOrErr;
const middleware = createErrorHandler();
return middleware(err2, req, res, next);
} else {
return createErrorHandler(optionsOrErr);
}
res.status(err.statusCode).json(response);
};
var error_default = errorHandler;
// src/errorHandler.ts
var ErrorHandler2 = class extends Error {
statusCode;
data;
constructor(message, statusCode, data) {
super(message);
this.statusCode = statusCode;
this.data = data;
Error.captureStackTrace(this, this.constructor);
}
};
var errorHandler_default = ErrorHandler2;
// Annotate the CommonJS export names for ESM import in node:

@@ -127,0 +178,0 @@ 0 && (module.exports = {

{
"name": "express-error-catcher",
"version": "1.0.1",
"version": "1.0.2",
"description": "async error handler",

@@ -9,3 +9,4 @@ "main": "./build/index.js",

"scripts": {
"build": "tsup"
"build": "tsup",
"dev": "nodemon"
},

@@ -28,6 +29,3 @@ "repository": {

],
"author": [
"thwahakp",
"uvaishassan"
],
"author": "",
"license": "ISC",

@@ -34,0 +32,0 @@ "bugs": {

@@ -0,15 +1,16 @@

# `express-error-catcher`
The `express-error-catcher` npm package provides a convenient solution for managing async/await errors in Node.js Express applications. The package is designed with simplicity in mind. Below are instructions on how to integrate and utilize `express-error-catcher` in your projects.
`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.
## Why Use `express-error-catcher`?
## Key Features
- Elimination of the need for extensive try-catch blocks in your asynchronous code.
- You can keep your route handlers clean and free from error-handling clutter.
- Enhances the readability of your code.
- Streamlines the development process.
- **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
To install `express-error-catcher`, use the following npm command:
Integrating `express-error-catcher` into your project is straightforward. Use the following npm command to install the package:

@@ -20,31 +21,51 @@ ```bash

## Example
## 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";
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();
// Error middleware for asyncErrorHandler to work
app.use(error);
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.
}));
```
// Example route with asyncErrorHandler
### 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) => {
// Throwing an error
asyncErrorHandler((req, res) => {
// Intentionally throwing an error
throw Error("Error while retrieving name", 500);
// Returning a response
// Returning a successful response
return Response("Successfully retrieved name", { name: "Daisy" }, 200);
})
);
```
// Start the Express app
### Step 4: Start the Express Server
Finally, start your Express server as usual:
```js
const PORT = process.env.PORT || 3000;

@@ -56,2 +77,115 @@ app.listen(PORT, () => {

## How does this work?
## 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.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc