Skip to content

Instantly share code, notes, and snippets.

@podhmo
Created February 16, 2024 10:12
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 podhmo/da9116f3137e64340b536f35b4ccefca to your computer and use it in GitHub Desktop.
Save podhmo/da9116f3137e64340b536f35b4ccefca to your computer and use it in GitHub Desktop.
import express from "express";
import process from "process";
async function main() {
const app = express();
const port = 3000;
app.get("/hello", (req, res) => {
res.send("Hello World!");
});
app.get("/error", (req, res) => {
throw new Error("hmm");
});
app.get("/async-error", async function (req, res, next) {
await doAsyncError();
});
app.get("/async-error2", async function (req, res, next) {
doAsyncError().catch(next);
});
app.get("/async-error3", async function (req, res, next) {
try {
await doAsyncError();
} catch (err) {
next(err);
}
});
app.use(function (err, req, res, next) {
log({ level: "error", err });
res.setHeader("content-type", "application/json");
res.status(500).send({ msg: "An error occurred", err });
});
app.listen(port, () => {
log({ msg: `start on port ${port}.` });
});
}
async function doAsyncError() {
try {
return await new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Something went wrong"));
}, 1000);
});
} catch (err) {
console.log("catch: **%s**", err)
throw err;
}
}
function log({ level = "info", msg, err }) {
if (err) {
console.log("========================================")
console.error(err);
console.log("========================================")
} else {
console.log("----------------------------------------")
console.log(`${level}: ${msg}`);
console.log("----------------------------------------")
}
}
main().then(() => console.log("done")).catch((e) => { console.error(e); process.exit(1); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment