-
-
Notifications
You must be signed in to change notification settings - Fork 173
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Handling errors in request handler #52
Comments
I eventually go for something like this instead. const polka = require('polka');
function handleError(err, req, res) {
// handle all errors here...
}
polka()
.get('/', async (req, res) => {
try {
const d = await doMoreStuff();
send(res, 200, d);
} catch (e) {
handleError(e, req, res);
}
})
.listen(3000); |
Hey, Yeah, there's no For now, my reasoning is that since you know there is an error to be thrown, you should just terminate the response directly. You can call a shared error handler as you've done, but IMO there's no reason to bubble up an error when you can just take care of it at the source. Only middleware functions have reason to bubble, since they're typically third-party and/or are handling preparatory work for your main handler & generally should not terminate the response cycle. This is an abbreviated version of what my applications typically look like: const { STATUS_CODES } = require('http');
const sendtype = require('@polka/send-type');
function toErr(res, code, data) {
let error = (data && data.message) || data || STATUS_CODES[code];
sendtype(res, code, { error });
}
function send(res, code, data) {
(code >= 400 ? toErr : sendtype)(res, code, data);
}
// here assumes no error is ignored
//~> runs for errors thrown in middleware loop
function onError(err, req, res, _next) {
toErr(res, err.code || err.status || 500, (err.length && err) || err.message);
}
polka({ onError })
.get('/:id', async (req, res) => {
try {
let d = await Post.find(req.params.id);
if (!d) return send(res, 404);
send(res, 200, d);
} catch (e) {
send(res, 500, e);
// or, if exported: onError(e, req, res);
}
})
.listen(PORT) |
@lukeed Thanks for the explanation and detailed code snippet. This looks like more sophisticated approach in handling errors using Polka. I learnt something today. Thank you so much. 👍 |
No problem, glad I could help! |
Not sure if this has been answered. I could find anything relevant here and I might have overlooked any similar issues.
This is something I encountered now.
This is what we normally would do in Express.
Please advise on how we can deal with such situation.
The text was updated successfully, but these errors were encountered: