0
0
Expressframework~10 mins

Error response formatting in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to send a JSON error response with status 404.

Express
app.get('/item/:id', (req, res) => {
  const item = database.find(i => i.id === req.params.id);
  if (!item) {
    return res.status([1]).json({ error: 'Item not found' });
  }
  res.json(item);
});
Drag options to blanks, or click blank then click option'
A200
B500
C404
D400
Attempts:
3 left
💡 Hint
Common Mistakes
Using status 200 for errors
Using status 500 for client errors
2fill in blank
medium

Complete the code to send a JSON error response with a custom message and status 400.

Express
app.post('/user', (req, res) => {
  if (!req.body.name) {
    return res.status([1]).json({ error: 'Name is required' });
  }
  res.json({ success: true });
});
Drag options to blanks, or click blank then click option'
A401
B404
C403
D400
Attempts:
3 left
💡 Hint
Common Mistakes
Using 401 which means unauthorized
Using 404 which means not found
3fill in blank
hard

Fix the error in the code to correctly send a JSON error response with status 500.

Express
app.get('/data', (req, res) => {
  try {
    const data = getData();
    res.json(data);
  } catch (error) {
    res.status([1]).json({ error: error.message });
  }
});
Drag options to blanks, or click blank then click option'
A500
B400
C404
D200
Attempts:
3 left
💡 Hint
Common Mistakes
Using res.send instead of res.json for JSON response
Using wrong status codes like 200 or 404
4fill in blank
hard

Fill both blanks to send a JSON error response with status 401 and a message.

Express
app.use((req, res) => {
  res.status([1]).json({
    error: [2]
  });
});
Drag options to blanks, or click blank then click option'
A401
B'Unauthorized access'
C'Not Found'
D403
Attempts:
3 left
💡 Hint
Common Mistakes
Using status 403 which means forbidden
Using error message 'Not Found' for unauthorized
5fill in blank
hard

Fill all three blanks to send a JSON error response with status 403 and a detailed message.

Express
app.get('/admin', (req, res) => {
  if (!req.user || !req.user.isAdmin) {
    return res.status([1]).json({
      error: [2],
      message: [3]
    });
  }
  res.json({ secret: '42' });
});
Drag options to blanks, or click blank then click option'
A401
B'Forbidden'
C'You do not have permission to access this resource.'
D403
Attempts:
3 left
💡 Hint
Common Mistakes
Using 401 instead of 403 for forbidden
Using vague or missing error messages