Skip to content

Instantly share code, notes, and snippets.

@tanmaiaccion
Last active August 13, 2020 12:44
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 tanmaiaccion/62a75f2b0aa0d3f7811919ee308d1429 to your computer and use it in GitHub Desktop.
Save tanmaiaccion/62a75f2b0aa0d3f7811919ee308d1429 to your computer and use it in GitHub Desktop.
class ResourceNotFoundError extends Error {
constructor(...args) {
super(...args);
this.trace = args[0];
this.name = "ResourceNotFoundError";
Error.captureStackTrace(this, ResourceNotFoundError);
}
}
const getUser = (user_id) => {
//if user_id exists in DB return user data
// else throw new ResourceNotFoundError()
}
let promisifyError = fn => (...args) => fn(...args).catch(args[2])
app.get("/user/:user_id", promisifyError( async (req, res) => {
let user = await getUser(req.params.user_id)
return res.json(user)
}))
app.use((err, req, res, next) => {
console.error(err.stack, err.name);
if (err.name == "ResourceNotFoundError") {
return res
.status(404)
.json({ err: err.trace.description });
}
return res.status(err.statusCode || 500).json({ err: err.stack });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment