Skip to content

Instantly share code, notes, and snippets.

@tonylampada
Created September 12, 2023 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonylampada/353545c6b9228a6ea7e42a5b10890cde to your computer and use it in GitHub Desktop.
Save tonylampada/353545c6b9228a6ea7e42a5b10890cde to your computer and use it in GitHub Desktop.
const express = require("express");
const request = require("supertest");
async function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
function _500errosync(req, res) {
throw new Error("Test error");
}
async function _500errorAsync(req, res) {
await sleep(100);
throw new Error("Test error async");
}
function interceptErrorMiddleware(err, req, res, next) {
if (err) {
console.error("it broke", err);
res.status(500).send("Something broke!");
}
}
function _createExpressApp() {
const app = express();
fixExpressErrorHandling(app);
app.get("/test-error-sync", _500errosync);
app.get("/test-error-async", _500errorAsync);
app.use(interceptErrorMiddleware);
return app;
}
function fixExpressErrorHandling(app) {
app.get = fixRoute(app.get);
app.post = fixRoute(app.post);
//etc
function fixRoute(route) {
return (path, ...handlers) => {
const newHandlers = handlers.map((handler) => {
return async (req, res, next) => {
try {
return await handler(req, res, next);
} catch (err) {
next(err);
}
};
});
route.call(app, path, ...newHandlers);
};
}
}
const app = _createExpressApp();
it("1. Sync error. No problem. Middleware got your back", async () => {
const response = await request(app).get("/test-error-sync");
expect(response.status).toBe(500);
expect(response.text).toBe("Something broke!");
});
it("2. Async error. Middleware doesn't catch it. Unless you fix express", async () => {
const response = await request(app).get("/test-error-async");
expect(response.status).toBe(500);
expect(response.text).toBe("Something broke!");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment