function wrapper to catch errors in express controllers
to install: npm i amk-wrap
can pass a function or a class method. Supports both CommonJS (require) and ESM (import).
The wrapped function must return a Promise (e.g., be async or return a Promise manually). Non-Promise return values will be rejected with a TypeError.
on the router file:
const express = require('express');
const router = express.Router();
const wrap = require('amk-wrap');
class Controller {
constructor() {
this.something = "something"
}
async get(req, res) {
this.something; // access this
res.send('hello world');
}
}
const controller = new Controller();
module.exports = function (controller) {
router.get('/', wrap(controller, 'get')); // pass a class method
return router;
}on the index.js:
const wrap = require('amk-wrap');
// some other code
app.get('/', wrap(getFunction)); // pass a functionor
const wrap = require('amk-wrap');
// some other code
app.get('/', wrap(async (req, res) => {
res.send('hello world');
}));import wrap from 'amk-wrap';
// some other code
app.get('/', wrap(getFunction)); // pass a functionor
import wrap from 'amk-wrap';
// some other code
app.get('/', wrap(async (req, res) => {
res.send('hello world');
}));amk-wrap ships with first-party type declarations. No additional @types/ package is required.
import wrap from 'amk-wrap';
import { Request, Response } from 'express';
app.get('/', wrap(async (req: Request, res: Response) => {
res.send('hello world');
}));- install dependencies using
npm install - run
npm test
All bugs, feature requests, pull requests, feedback, etc., are welcome. Create an issue.