Created
September 12, 2023 10:39
-
-
Save tonylampada/353545c6b9228a6ea7e42a5b10890cde to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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