Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 446
A Little Girl Avatar asked Nov 02 '25 17:11

A Little Girl


1 Answers

Nothing, based on the source code.

  try {
    fn(req, res, next);
  } catch (err) {
    next(err);
  }
like image 181
AKX Avatar answered Nov 05 '25 07:11

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!