I'm using express with async/await. When an async function is rejected, exception is thrown.
However, the client will not get a response for his request, leaving him hanging in the air.
How should I add a global exception handler for unhandled runtime exceptions? On these cases, server should reply with "Server Error" status code 500.
- I don't want to wrap all of my server side functions with
tryandcatch - I don't want to hint the next request handler there was an error (e.g.
next(err);) - I've read https://expressjs.com/en/guide/error-handling.html, couldn't find something as simple as I describe (have I missed something?)
This is my example express app:
const express = require('express');
const app = express();
const port = 8080;
async function validate() {
let shouldFail = Math.random() >= 0.5;
if (shouldFail) {
throw new Error();
}
}
app.get('/', async (req, res) => {
await validate();
res.json({"foo": "bar"});
});
app.listen(port, () => console.log(`listening on port ${port}!`));
Note - the http function will fail randomly. It's just for demo purposes.