When express App run syncronous code:
app.get("/test", (req, res) => {
throw new Error("Oh no! The world has ended!");
});
Those code works fine.
But when run Asyncronous code:
app.get("/test", async (req, res) => {
throw new Error("Oh no! The world has ended!");
});
It has problem.
1. Using 'next':
app.get("/test", async (req, res, next) => {
next(throw new Error("Oh no! The world has ended!"));
});
2. Using try/catch:
app.get("/test", async (req, res) => {
try {
throw new Error("Oh no! The world has ended!");
} catch(error) {
next(error)
}
});
3. Library: express-async-errors
const express = require("express");
const app = express();
require("express-async-errors");
app.get("/test", async (req, res) => {
throw new Error("Oh no! The world has ended!");
});
4. Custom middleware:
const { errorHandling } = require("./utils/error");
app.get("/test", async (req, res) => {
throw new Error("Oh no! The world has ended!");
});
app.use(errorHandling); // keep it as last step
app.listen(3001, function () {
console.log("Server started.");
});
function errorHandling(error, req, res, next) { if (res.headersSent) { next(error); } else { res.status(500); res.json({ message: error.message, ...(process.env.NODE_ENV === "production" ? null : { stack: error.stack }), }); } } module.exports = { errorHandling };