GaryO
GaryO

Reputation: 6338

How to catch async errors in nodejs Express outside request context?

I have a simple express server where a POST request kicks off a long-running job and returns a job ID. The server monitors the job status and the client can query for the job status over time. I do this with child_process.spawn, and have callbacks for the usual events on the child_process.

Sometimes an exception will happen during the job's execution, long after the initial "start job" request has returned. That calls my error callback, but then what? I can't throw an ApiError there, because express won't handle it -- I'll get an UnhandledPromiseRejectionWarning (which in a future node.js version will terminate the process).

Is there any way to set up a "global error handler" for express that would put a try/catch around the whole server?

A simple example would be something like this:

app.post('/testing', (req, res) => {
  setTimeout(() => { raise new ApiError('oops!') }, 1000)
})

Upvotes: 1

Views: 1928

Answers (1)

laxman
laxman

Reputation: 2110

straight from express docs,

"You must catch errors that occur in asynchronous code invoked by route handlers or middleware and pass them to Express for processing. For example:"

app.get('/testing', function (req, res, next) {
  setTimeout(function () {
    try {
      throw new Error('BROKEN')
    } catch (err) {
      next(err)
    }
  }, 100)
})

Upvotes: 2

Related Questions