Last active
August 13, 2020 12:44
-
-
Save tanmaiaccion/62a75f2b0aa0d3f7811919ee308d1429 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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