next-session
next-session copied to clipboard
UnhandledPromiseRejectionWarning when an error occurred in session auto commit
Hi! I'm writing a custom Sequelize Store for one of my projects. The error happens when next-session is trying to commit a session. As far as I can tell from the logs, the error appears in this function: https://github.com/hoangvvo/next-session/blob/07a200b979d5204a83d35f8c2de93ec25583eda1/src/core.ts#L54-L57
Perhaps having error handler within the res.end() would fix that problem?
If you want to see the error in action, just clone this repo and throw any error from Store#set() method and then open /api/auth/login.
Or just do the same thing in MemoryStore, it should work same way :)
How should the error be handled in this case? Should we just let res.end calls and sends the response as usual (silent error) or should we call res.end with the error message?
Well, in my case, I use the library alongside with next-connect, so I expect an error to be forwarded to their onError callback. Not sure for other cases, but I think it would depend on how do developers compose their API handler with your library. I don't think is that an error should be silenced anyway.
My bad, when I say silent I mean not reporting anything to the front-end and display things as usual. Of course, I would do some console.error when it occurs.
This library (and express-session too) , use a "hack" to save the session on response by "rewriting" the res.end function into an async function like you see above. There is no way to really catch the error with next-connect because res.end is never called with await and error in a async function is lost without doing so (or attaching a .catch).
What we can do is to handle the error in the library. What I mentioned earlier was that we had two options:
Send the error response instead of the original.
res.end = async function resEndProxy(...args: any) {
try {
await req.session.save();
} catch(e) {
return oldEnd.call(this, e.message)
// Or instead e.message just "An error occurred
// The original response is never sent
}
oldEnd.apply(this, args);
};
This is what I meant by "silent"
res.end = async function resEndProxy(...args: any) {
try {
await req.session.save();
} catch(e) {
console.error(e);
// Log the error but let the response goes out as usual
}
oldEnd.apply(this, args);
};
Either way, we next-connect cannot catch the error unfortunately.
Sorry I've never answered. I'm closing this, because I don't use this library anymore, so issue is not relatable for me as well.