Package Exports
- tranxpress
- tranxpress/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (tranxpress) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
๐ง tranxpress
An elegant, extensible, and fully TypeScript-supported async handler utility for Express.js that simplifies error handling, supports MongoDB transactions, and allows nested error handlers for next-level control.
๐ Features
- ๐ Wrap async/await routes and middlewares without try-catch hell.
- ๐งฉ Optional MongoDB transactions using Mongoose sessions.
- ๐ Nested
asyncHandler
support (yes, recursion like a boss). - ๐ Smart MongoDB error parsing with stack trace and error code support.
- ๐ ๏ธ Plug-in custom error handlers at any depth.
- โ Built-in TypeScript typings for safety and autocompletion bliss.
- ๐ฆ Includes extendable
ErrorResponse
andSuccessResponse
classes.
๐ฆ Installation
npm install tranxpress
If you're using TypeScript and Express:
npm install --save-dev @types/express
๐งโ๐ป Usage
Basic Example
import express from "express";
import { asyncHandler } from "tranxpress";
const app = express();
app.get(
"/ping",
asyncHandler(async (req, res) => {
// simulate async error
throw new Error("Boom ๐ฅ");
})
);
๐ผ With MongoDB Transaction (Mongoose)
app.post(
"/create-user",
asyncHandler(async (req, res) => {
const session = req.session;
const user = await User.create([{ name: "iBoon" }], { session });
res.json({ user });
}, { useTransaction: true })
);
req.session
is automatically injected ifuseTransaction
is true.
๐งฌ Nested Error Handlers
You can define a hierarchy of error handlers using asyncHandler
recursively.
const deepestHandler = asyncHandler(async (err, req, res) => {
console.log("๐ฅ Deep nested handler:", err.message);
});
const middleHandler = asyncHandler(async (err, req, res) => {
console.log("๐งฉ Middle layer handling error...");
throw err; // pass to next handler
}, { customErrorHandler: deepestHandler });
app.get(
"/crash",
asyncHandler(async (req, res) => {
throw new Error("Nested Boom ๐ฃ");
}, { customErrorHandler: middleHandler })
);
๐ฆ Advanced MongoDB Error Handling
The package includes a robust MongoHandledError
wrapper class.
throw new MongoHandledError(originalMongoError);
It parses common errors like:
ValidationError
โ 400CastError
โ 400MongoServerError
โ 500DuplicateKeyError
(code11000
) โ 409
The error contains:
{
message: "Duplicate key error",
statusCode: 409,
stack: "...",
code: 11000
}
๐งฐ API Reference
asyncHandler(fn, options?)
Param | Type | Description |
---|---|---|
fn |
(req, res, next) => {} |
The async route/controller function |
options.useTransaction |
boolean |
Enable MongoDB transaction (Mongoose) |
options.customErrorHandler |
AsyncFn |
Another asyncHandler or custom error logic |
โ Response Classes
ErrorResponse
Use this to throw custom errors.
import { ErrorResponse } from "tranxpress";
throw new ErrorResponse("Invalid input", 400, { field: "email" });
You can extend it:
class CustomError extends ErrorResponse {
constructor(message: string) {
super(message, 422);
}
}
SuccessResponse
Use this for consistent success responses.
import { SuccessResponse } from "tranxpress";
res.status(200).json(new SuccessResponse("User created", { user }));
๐ Error Object Structure
If the handler catches an error, it forwards:
{
message: "Something went wrong",
statusCode: 500
}
You can access more details if needed:
error.code
error.stack
error.reason
๐งช Testing It Out
You can test it with this setup:
app.use((err, req, res, next) => {
res.status(err.statusCode || 500).json({
error: err.message,
stack: process.env.NODE_ENV === "development" ? err.stack : undefined
});
});
โณ Suggested Folder Structure
๐ฆ src/
โโโ asyncHandler.ts
โโโ utils/
โ โโโ mongoErrorHandler.ts
โโโ responses/
โ โโโ ErrorResponse.ts
โ โโโ SuccessResponse.ts
โโโ types/
โ โโโ sharedTypes.ts
๐ Keywords
express, middleware, async handler, async middleware, typescript, error handler, mongoose, transaction, mongodb, nested error handler, api wrapper, clean error handling, success response, error response
๐ง Future Ideas
- ๐ Localization support for user-friendly error messages.
- ๐ง Limit recursion depth for nested handlers.
- ๐งช Built-in test utils (mocking sessions, errors, etc).
๐งโ๐ Author
Made with โค๏ธ by [iBoon Technologies].
Ready to handle errors like a pro?
Use tranxpress
and say goodbye to callback hell forever. ๐