-
-
Save rwillians/a58df88819cf1f7b32f8449e76804cd0 to your computer and use it in GitHub Desktop.
express rescue
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
const rescue = require('express-rescue') | |
class UserNotFound extends Error {} | |
// ... | |
app.get('/users/:id', [ | |
rescue(async (req, res) => { | |
throw new UserNotFound(/* ... */) | |
}, | |
resuce.from(UserNotFound, (err, req, res) => { | |
res.status(404) | |
.json({ message: 'user not found' }) | |
}) | |
]) |
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
const rescue = require('express-rescue') | |
class UserNotFound extends Error {} | |
class HttpError extends Error{ | |
constructor({ status, message }) { /* ... */ } | |
} | |
class NotFound extends HttpError { | |
constructor(message) { super({ status: 404, message }) } | |
} | |
// ... | |
app.get('/users/:id', [ | |
rescue(async (req, res) => { | |
throw new UserNotFound(/* ... */) | |
}, | |
resuce.from(UserNotFound, (err, req, res) => { | |
throw new NotFound('user not found') | |
}) | |
]) | |
app.use(rescue.from(HttpError, (err, req, res) => { | |
res.status(err.status) | |
.json({ message: err.message }) | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment