In my services using express nodejs. I knew about the express error handler, the callback function with err first
app.use(function(err, req, res, next)
And We can handle the uncaughtException also by
process.on('uncaughtException', function(err) {}
In fact, some uncaughtException will go to express error handler not uncaughtException handler.
Please help to tell me which error will be handled by express, which by uncaughtException handler?
Many thanks
When you throw an exception (
throw new Error(...)
) in a function that was directly called from Express, it will be catched and forwarded it to your error handler. This happens because there's atry-catch
block around your code.When you throw an exception in a function that is not directly called from Express (deferred or async code), there's no catch block available to catch this error and handle it properly. For example, if you have code that gets executed asynchronously:
This error won't be catched by Express (and forwarded to the error handler) because there's no wrapping try/catch block around this code. In this case, the uncaught exception handler will be triggered instead.
In general, if you encounter an error from which you cannot recover, use
next(error)
to properly forward this error to your error handler middleware:Below is a full example to play around with: