Bird
Raised Fist0
Node.jsframework~10 mins

Centralized error handling in Node.js - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a basic Express error handler middleware.

Node.js
app.use(function(err, req, res, [1]) {
  res.status(500).send('Something broke!');
});
Drag options to blanks, or click blank then click option'
Anext
Berror
Cresponse
Drequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' instead of 'next' as the last parameter.
Missing the fourth parameter entirely.
2fill in blank
medium

Complete the code to forward an error to the centralized error handler.

Node.js
app.get('/', (req, res, [1]) => {
  const err = new Error('Oops!');
  [1](err);
});
Drag options to blanks, or click blank then click option'
Anext
Berror
Chandle
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' or 'handle' instead of 'next'.
Not calling any function to forward the error.
3fill in blank
hard

Fix the error in the centralized error handler to send JSON response.

Node.js
app.use((err, req, res, next) => {
  res.status(500).[1]({ error: err.message });
});
Drag options to blanks, or click blank then click option'
AsendFile
BsendText
Cjson
Drender
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'sendText' or 'render' which are not valid methods for JSON response.
Forgetting to send the error message in JSON format.
4fill in blank
hard

Fill both blanks to create a middleware that catches 404 errors and forwards them to the error handler.

Node.js
app.use((req, res, [1]) => {
  const err = new Error('Not Found');
  err.status = 404;
  [2](err);
});
Drag options to blanks, or click blank then click option'
Anext
Berror
Dsend
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'error' or 'send' instead of 'next'.
Not forwarding the error to the next middleware.
5fill in blank
hard

Fill all three blanks to create a centralized error handler that logs the error, sets status, and sends JSON response.

Node.js
app.use((err, req, res, [1]) => {
  console.error(err.[2]);
  res.status(err.status || 500).[3]({ message: err.message });
});
Drag options to blanks, or click blank then click option'
Anext
Bstack
Cjson
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Logging 'message' instead of 'stack'.
Using 'send' instead of 'json' for response.
Missing the 'next' parameter.

Practice

(1/5)
1. What is the main benefit of centralized error handling in a Node.js Express app?
easy
A. It keeps all error handling code in one place for easier maintenance.
B. It automatically fixes all errors without developer input.
C. It prevents any errors from occurring in the app.
D. It makes the app run faster by skipping error checks.

Solution

  1. Step 1: Understand centralized error handling purpose

    Centralized error handling means managing errors in one place instead of scattering code everywhere.
  2. Step 2: Identify benefits of centralized error handling

    This approach makes the app easier to maintain and debug because all error logic is together.
  3. Final Answer:

    It keeps all error handling code in one place for easier maintenance. -> Option A
  4. Quick Check:

    Centralized error handling = easier maintenance [OK]
Hint: Centralized means one place for all errors [OK]
Common Mistakes:
  • Thinking it prevents errors automatically
  • Believing it makes the app faster by skipping errors
  • Confusing centralized handling with error fixing
2. Which of the following is the correct signature for an Express centralized error handling middleware?
easy
A. function errorHandler(req, res, next) { ... }
B. function errorHandler(err, req, res, next) { ... }
C. function errorHandler(err, req, res) { ... }
D. function errorHandler(req, res) { ... }

Solution

  1. Step 1: Recall Express error middleware signature

    Express error middleware must have four parameters: error, request, response, next.
  2. Step 2: Match the correct function signature

    Only the function with (err, req, res, next) matches the required signature.
  3. Final Answer:

    function errorHandler(err, req, res, next) { ... } -> Option B
  4. Quick Check:

    Error middleware = 4 params (err, req, res, next) [OK]
Hint: Error middleware always has 4 parameters [OK]
Common Mistakes:
  • Using 3 parameters instead of 4
  • Omitting the error parameter
  • Confusing normal middleware with error middleware
3. Given this Express app code snippet, what will be the response when a GET request to '/' throws an error?
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  throw new Error('Oops!');
});

app.use((err, req, res, next) => {
  res.status(500).send('Error caught: ' + err.message);
});

app.listen(3000);
medium
A. The server crashes and no response is sent.
B. The client receives a default Express error page with status 404.
C. The client receives 'Error caught: Oops!' with status 500.
D. The client receives 'Oops!' with status 200.

Solution

  1. Step 1: Identify error throwing in route

    The GET '/' route throws an error with message 'Oops!'.
  2. Step 2: Check error middleware handling

    The error middleware catches the error and sends a 500 status with message 'Error caught: Oops!'.
  3. Final Answer:

    The client receives 'Error caught: Oops!' with status 500. -> Option C
  4. Quick Check:

    Thrown error caught by middleware = 500 response [OK]
Hint: Thrown errors go to error middleware response [OK]
Common Mistakes:
  • Assuming server crashes on thrown error
  • Expecting status 404 instead of 500
  • Thinking error message is sent without prefix
4. What is wrong with this Express error handling middleware?
app.use((err, req, res) => {
  res.status(500).send('Error: ' + err.message);
});
medium
A. It is missing the 'next' parameter, so Express won't recognize it as error middleware.
B. It should not use res.status(500) inside error middleware.
C. The error parameter should be named 'error' instead of 'err'.
D. It should be placed before route handlers, not after.

Solution

  1. Step 1: Check middleware parameters

    Express error middleware requires four parameters: err, req, res, next.
  2. Step 2: Identify missing parameter

    This middleware has only three parameters, missing 'next', so Express treats it as normal middleware, not error handler.
  3. Final Answer:

    It is missing the 'next' parameter, so Express won't recognize it as error middleware. -> Option A
  4. Quick Check:

    Error middleware must have 4 params (err, req, res, next) [OK]
Hint: Error middleware always needs 4 parameters [OK]
Common Mistakes:
  • Thinking parameter names must be specific
  • Believing status code usage is wrong
  • Placing middleware order incorrectly
5. You want to create a centralized error handler that logs errors and sends JSON responses with status and message. Which code snippet correctly implements this in Express?
hard
A. app.use((err, req, res, next) => { res.sendStatus(200); });
B. app.use((req, res, next) => { console.error('Error occurred'); res.status(500).json({ error: 'Unknown error' }); });
C. app.use((err, req, res) => { console.log(err); res.send('Error happened'); });
D. app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); });

Solution

  1. Step 1: Verify error middleware signature and logging

    The correct snippet uses four parameters (err, req, res, next) and logs the error stack with console.error(err.stack).
  2. Step 2: Check response format and status code

    It sends a JSON response with the error message and sets the status to err.status || 500.
  3. Step 3: Evaluate other options

    The other options lack the proper signature, correct logging, status handling, or JSON response.
  4. Final Answer:

    app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); }); -> Option D
  5. Quick Check:

    Proper error middleware logs and sends JSON with status [OK]
Hint: Error middleware: 4 params, log error, send JSON with status [OK]
Common Mistakes:
  • Missing 'next' parameter in middleware
  • Sending status 200 on error
  • Not sending JSON response format