0

Using express I have one REST route where I fetch some data. Within this request I also add an entry into an event table (for app insights purposes) in the database. I do not really care to wait for that event to be saved before returning the actual data to the requester, since saving the event is not that important for the end user.

Something like this pseudo code:

const data = await getResponseDataFromDatabase();

insertInsightsEventIntoDatabase(); // returns a promise which I don't want to wait for

return data;

Since there was a bug in the insertInsightsEventIntoDatabase I got this error in the logs:

This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason:
Error: Cannot set headers after they are sent to the client

If I await the insertInsightsEventIntoDatabase() I would get a much better error log in the console that shows an error from the ORM I am using.

My question is, it it wrong to not await the method? I like the idea of not awaiting it just to have it "run in the background" and not blocking the time it takes to send the response on the client request. The drawback is that the real error seems to be swallowed and I would very much like to have the original error in the logs.

Am I doing this wrong?

rablentain
  • 6,641
  • 13
  • 50
  • 91
  • 1
    It's not wrong to not `await` the promise (for having the task continue in the background), but whenever a promise chain ends you should `.catch()` and handle the errors from it. – Bergi Jun 14 '22 at 12:25
  • Alright. I want to have the same error logs as if I would have awaited the method. Would that be `.catch((e) => console.log(e))`? How about Sentry which I am using, I would like Sentry to pick these errors up as well without manually calling Sentry in the catch block. – rablentain Jun 14 '22 at 12:35
  • 1
    You mention getting an error from your ORM if you use `await` - where and how does the ORM `catch` the error? You'd need to reproduce that. I don't think you can get Sentry logging without manually calling it - Sentry does watch for unhandled rejections and unhandled exceptions itself, but those crash the process, and it sounds like you don't want that. – Bergi Jun 14 '22 at 20:16

0 Answers0