FAQ: Middleware - Error-Handling Middleware

This community-built FAQ covers the “Error-Handling Middleware” exercise from the lesson “Middleware”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Learn Express

FAQs on the exercise Error-Handling Middleware

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hi Team,

Part 2 on exercise 12 of 15 asks to refactor the error routes.

I have done this but get a syntax error. I’ve gone through the test.js script and I have kept all spelling and grammar the same. Any ideas where I have gone wrong?

const express = require(‘express’);
const app = express();
const morgan = require(‘morgan’);
const bodyParser = require(‘body-parser’);

app.use(express.static(‘public’));

const PORT = process.env.PORT || 4001;

const jellybeanBag = {
mystery: {
number: 4
},
lemon: {
number: 5
},
rootBeer: {
number: 25
},
cherry: {
number: 3
},
licorice: {
number: 1
}
};

// Body-parsing Middleware
app.use(bodyParser.json());

// Logging Middleware
if (process.env.IS_TEST_ENV) {
app.use(morgan(‘dev’));
}

app.use(’/beans/:beanName’, (req, res, next) => {
const beanName = req.params.beanName;
if (!jellybeanBag[beanName]) {
const err = new Error(‘Bean with that name does not exist’);
err.status = 404;
return next(err);
}
req.bean = jellybeanBag[beanName];
req.beanName = beanName;
next();
});

app.get(’/beans/’, (req, res, next) => {
res.send(jellybeanBag);
});

app.post(’/beans/’, (req, res, next) => {
const body = req.body;
const beanName = body.name;
if (jellybeanBag[beanName] || jellybeanBag[beanName] === 0) {
const err = new Error(‘Bean with that name already exists!’);
err.status = 400;
return next(err);
}
const numberOfBeans = Number(body.number) || 0;
jellybeanBag[beanName] = {
number: numberOfBeans
};
res.send(jellybeanBag[beanName]);
});

app.get(’/beans/:beanName’, (req, res, next) => {
res.send(req.bean);
});

app.post(’/beans/:beanName/add’, (req, res, next) => {
const numberOfBeans = Number(req.body.number) || 0;
req.bean.number += numberOfBeans;
res.send(req.bean);
});

app.post(’/beans/:beanName/remove’, (req, res, next) => {
const numberOfBeans = Number(req.body.number) || 0;
if (req.bean.number < numberOfBeans) {
const err = new Error(‘Not enough beans in the jar to remove!’);
err.status = 400;
return next(err);
}
req.bean.number -= numberOfBeans;
res.send(req.bean);
});

app.delete(’/beans/:beanName’, (req, res, next) => {
const beanName = req.beanName;
jellybeanBag[beanName] = null;
res.status(204).send();
});

// Add your error handler here:
app.use((err, req, res, next) => {
const status = err.status || 500;
res.status(status).send(err.message);
});

app.listen(PORT, () => {
console.log(Server is listening on port ${PORT});
});

I’m lost with this lesson on error-handling.

First of all, I don’t understand the following line:

let undefinedError = new Error('newValue was not defined!');

What’s this Error class? Does it create an error message string?

Second, with the following code of lines:

let undefinedError = new Error('newValue was not defined!');
return next(undefinedError);

which error-handling middleware does it prompt? Is it the one defined by

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

or something else?

Finally, in exercise 2, the hint suggests replacing

return res.status(404).send('error!');

with

const err = new Error('error!');
err.status = 400;
return next(err);

But this will duplicate lots of code, against the principle that we have learned in this unit…

1 Like

Did you ever figure this out? I am having the same issue, getting a “can’t set headers after they are sent” syntax error.

I copied your code into my interpreter and got an error, but from the resulting error message it looks like the problem has to do with the character you’re using as a single-quote. It shows up as a different color and shape on my screen; maybe it’s an apostrophe character?

This is your character: ‘
This is the one I use: ’

(https://stackoverflow.com/questions/6711892/right-single-apostrophe-vs-apostrophe)

Error I got: (formatting may screw up the paste-job but that carrot character is suppose to be pointing at the single-quote of “require(‘express’);”)

/home/ccuser/workspace/learn-express-middleware-error-handling-middleware/app.js:1
(function (exports, require, module, __filename, __dirname) { const express = require(‘express’);
^
SyntaxError: Invalid or unexpected token

Question on the .status() method – where can it be used? I initially tried to set the status on my error object with it, but that obviously didn’t work and I had to use a normal assignment statement.

e.g. To send the status in the response:
res.status(404).send('The requested resource was not found');

e.g. To set the status of the error that will be passed to the error handler:

const notFoundErr = new Error('The requested resource was not found');
notFoundErr.status = 404;
next(notFoundErr);

That suggestion is just an example. In our code each ‘err’ should have a unique message defined by ‘new Error(‘Unique Error Message here’)’ and a specific ‘err.status’ value which may or may not be unique (400, 404, etc).

You could define an error handling function which takes two arguments ‘errorHandler(message, status)’ and call it in place of the three error statements but I’m not sure how many key strokes that’s gonna save you.

Hope this helps.

An Error in the Exercise:

In the exercise, even if you program it correctly it will throw a ‘Syntax Error’ because there is an ‘Error’ in the initial program when we begin the exercise. (Meaning, it’s NOT your fault!).

The problem is with the following line of code at the very top:

// Logging Middleware
if (process.env.IS_TEST_ENV) {
app.use(morgan(‘dev’));
};

There should be an exclamation point BEFORE process in the If statement conditional. like below:
// Logging Middleware
if (!process.env.IS_TEST_ENV) {
app.use(morgan(‘dev’));
}

Make sure you make this change before you ‘Check Work’ in step 2 or else you’ll get an error.

Hope this saves you some troubleshooting time!

3 Likes

Hi guys,

‘‘When an error is thrown somewhere in our code, we want to be able to communicate that there was a problem to the user.’’ Where should I find this error message in this exercise?

I couldn’t find any error message like ‘Bean with that name does not exist’ (neither on the webpage nor the console) after giving a bad request when I passed all instructions, I even tried the solution from Codecademy but still didn’t work. Let me give one of my bad request for you, e.g., I POST the route /beans/ than I typed name mystery which already exists in our jellybeanBag object.I could only see the status code, but there was no error message. I had also tried other bad requests and end up with the same result.

Why is this so? Have anyone encountered the same situation or did I do something wrong?

I went over and over my code and could not figure out why it was not passing. This fixed it right away.

Thanks!

I have replaced all the code as requested - this is my new error handling:

app.use('/beans/:beanName', (req, res, next) => {
  const beanName = req.params.beanName;
  if (!jellybeanBag[beanName]) {
    const newError = new Error('Bean with that name does not exists');
    newError.status = 404;
    return next(newError);
  }
  req.bean = jellybeanBag[beanName];
  req.beanName = beanName;
  next();
});

But all I’m getting when checking work is

Does your `app.use` handler for /beans/:beanName still send the same response text for invalid names?

I am literally stuck because I don’t know what is wrong with it and any help would be much appreciated.

Apparently, the problem was me writing “exists” instead of “exist”. Spent one day to try to figure out what was I doing wrong. Is this what programming really is? :frowning_face:

1 Like

I have a question.

where do we set this value?

(process.env.IS_TEST_ENV)

how to be set these values in proces.env?

Yep had a similar issue, I kept failing because I used an exclamation mark at the end of my beanName error message…

Mine did the same thing until I swapped my const err for error. It wouldn’t pass me just because I didn’t use declare the err variable exactly like the solution.

my code:

 const err = new Error('Bean with that name already exists!')
    err.status = 400;
    return next(err);

solution:

 const error = new Error('Bean with that name already exists!')
    error.status = 400;
    return next(error);
1 Like

Hey all!

Before we required the errirhandler middleware function from the express webpage we had to put our own error handling function at the end of the code right before app.listen(). In the task with requiring errorhandler we put an app.use() right on the next line, that is NOT at the end of the code before app.listen(). I understand why in the first part we put the error handling function as the last app.use(). I wonder why we don’t do that with the errorhandler as well. Thanks!

1 Like

Following. Have you found out? I have the same question

Asked the same question in the FAQ to that task, which is 2 years old - I have no clue either and would be immensely grateful if somebody could explain what the heck that last task is talking about or what the ‘catch-all error handler’ that was supposedly replaced was (nothing had been replaced in the solution code?)

The express module has been pretty dire tbh, still not convinced I truly understand a lot of what was presented and the gaps in my understanding are making it incredibly difficult to even search for answers with Google because I don’t know exactly what it is I need to ask to find the explanations I need

Even something as simple as “how to use express errorhandler middleware” has yielded absolutely nothing besides the official documentation, which explains nothing in terms that make any sense compared to what was in the Express module I just finished

The only thing I ask myself in this exercise is, whether this code is supposed to simplify things.