Skip to content

Instantly share code, notes, and snippets.

@olehcambel
Last active January 3, 2019 16:03
Show Gist options
  • Save olehcambel/474da3a956fdde29b8e87bfe8254f62a to your computer and use it in GitHub Desktop.
Save olehcambel/474da3a956fdde29b8e87bfe8254f62a to your computer and use it in GitHub Desktop.
How to handle async errors?
const app = require('express')();
const getConvert = async (req, res, next) => {
try {
throw 'err';
} catch (err) {
next(err)
}
};
app.get('/', getConvert);
app.use((err, req, res, next) => {
res.status(500).send('~~~');
});
app.listen(9000);
const app = require('express')();
const catchErr = fn => async (req, res, next) => {
try {
await fn(req, res, next);
} catch (err) {
next(err);
}
};
const getConvert = async (req, res, next) => {
throw 'err';
};
app.get('/', catchErr(getConvert));
app.use((err, req, res, next) => {
res.status(500).send('~~~');
});
app.listen(9000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment