Estus Flask
Estus Flask

Reputation: 222498

Disable Express error handling for critical errors

app.use(function (req, res, next) {
    throw new Error('critical');
})

makes Express server to catch a critical error and output it, while I want it to crash.

Adding an error handler doesn't replace the default handler.

How can Express error handling be disabled for critical errors?

Upvotes: 3

Views: 4607

Answers (1)

Andy Carlson
Andy Carlson

Reputation: 3909

If you want your server to crash in the event of a critical error, you can define an error-handling middleware. This is done by defining a function with 4 parameters, the first being the error. This will be called when an error is thrown. You can check the error and determine if it's critical, and if so, call process.exit.

const app = require('express')()

app.use('/', (req, res) => {
  throw new Error('critical')
})

app.use((err, req, res, next) => {
  if (err.message === 'critical') {
    process.exit(1)
  } else {
    // carry on listening
  }
})

Upvotes: 5

Related Questions