0

My question is how can I add error handling for this very simple Node.js/Express server? It can just console.log errors. Should it be a part of app.post ?

const app = require('express')();
const bodyParser = require('body-parser');
const cors = require('cors');

const secretNumber = Math.floor(Math.random() * 10000) + 1;

app.use(cors());

app.use(bodyParser.json());

app.post('/number', (req, res) => {

  const guess = req.body.isNumber;

  if (guess < secretNumber) {
    res.json({
      resultText: 'The number that you are searching for is higher than yor guess.',
      resultCode: 'higher',
      yourGuess: guess
    });
  } else if (guess > secretNumber) {
    res.json({
      resultText: 'The number that you are searching for is lower than yor guess.',
      resultCode: 'lower',
      yourGuess: guess
    });
  } else {
    res.json({
      resultText: 'Congratulations! You have just found the secret number!',
      resultCode: 'success',
      yourGuess: guess
    });
  }

});


app.listen(3001, () => console.log('Listening on port 3001.'));

I found code like this:

function errorHandler (err, req, res, next) {
  res.status(500)
  res.render('error', { error: err })
}

But I don't know where exactly should I put it.

1 Answer 1

1

In your routes, you forward the error to the next function and your last middleware should handle it.

app.post('/number', (req, res, next) => {

  const guess = req.body.isNumber;

  if (guess < secretNumber) {
    res.json({
      resultText: 'The number that you are searching for is higher than yor guess.',
      resultCode: 'higher',
      yourGuess: guess
    });
  } else if (guess > secretNumber) {
  // Error here for example!!
   next(new Error('My error msg :)'))
  } else {
    res.json({
      resultText: 'Congratulations! You have just found the secret number!',
      resultCode: 'success',
      yourGuess: guess
    });
  }

});

// Error handler
app.use(function(err, req, res, next) {
  res.status(500)
  res.json({ error: err.message })
});


app.listen(3001, () => console.log('Listening on port 3001.'));

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.