Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What are different between next(error) and throw new Error in Express framework?

Can someone explain to me about the different between two ways exception error handling in code Express JS below:

const express = require('express');
const app = express();

app.get('/test', (req, res, next) => {

  // the first way:
  throw new Error('my error message');

  // the second way:
  next(new Error('my error message'));

});

app.use((err, req, res, next) => {
  res.status(err.status || 500).send(err.message || 'Internal Server Error');
});

app.listen(3000, () => console.log('Welcome to ExpressJS'));

It returns the same result handled by error middleware but what is the difference here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Nothing, based on the source code.

  try {
    fn(req, res, next);
  } catch (err) {
    next(err);
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading