Bird
Raised Fist0
Expressframework~20 mins

Validation error response formatting in Express - Practice Problems & Coding Challenges

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
Challenge - 5 Problems
🎖️
Express Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this Express validation error handler?
Consider this Express middleware that handles validation errors. What JSON response will the client receive if a validation error occurs?
Express
app.use((err, req, res, next) => {
  if (err.isValidationError) {
    return res.status(400).json({
      error: {
        message: err.message,
        fields: err.fields
      }
    });
  }
  next(err);
});
A{"error":{"message":"Invalid input","fields":{"email":"Invalid format"}}}
B{"message":"Invalid input","fields":{"email":"Invalid format"}}
C{"error":"Invalid input","fields":{"email":"Invalid format"}}
D{"status":400,"error":"Invalid input"}
Attempts:
2 left
💡 Hint
Look at the structure inside the json() call and how the error object is nested.
📝 Syntax
intermediate
2:00remaining
Which option correctly formats a validation error response in Express?
You want to send a 422 status with a JSON body containing an error message and an array of invalid fields. Which code snippet is correct?
Ares.status(422).send({ error: { message: "Invalid data", fields: ["name", "email"] } });
Bres.status(422).json({ message: "Invalid data", fields: ["name", "email"] });
Cres.status(422).json({ error: { message: "Invalid data", fields: ["name", "email"] } });
Dres.json(422, { error: { message: "Invalid data", fields: ["name", "email"] } });
Attempts:
2 left
💡 Hint
Check the correct order of method chaining and JSON response method in Express.
🔧 Debug
advanced
2:00remaining
Why does this validation error response not send the expected JSON?
This Express middleware tries to send a validation error response but the client receives an empty response. What is the issue?
Express
app.use((err, req, res, next) => {
  if (err.isValidationError) {
    res.status(400);
    res.json({ error: err.message });
    return;
  }
  next(err);
});
AThe middleware calls next(err) after sending a response, causing Express to override the response with an empty one.
Bres.status(400) is not chained with res.json(), so status code is ignored.
CThe error object is missing a fields property, so JSON is empty.
DMiddleware must end with return statement to send response properly.
Attempts:
2 left
💡 Hint
Think about what happens when next() is called after sending a response.
state_output
advanced
2:00remaining
What is the status code and JSON response sent by this validation error handler?
Given this Express error handler, what status code and JSON does the client receive when a validation error occurs?
Express
app.use((err, req, res, next) => {
  if (err.isValidationError) {
    res.status(422).json({
      error: {
        message: err.message,
        invalidFields: err.invalidFields
      }
    });
  } else {
    res.status(500).json({ error: "Internal Server Error" });
  }
});
AStatus: 500, JSON: {"error":"Internal Server Error"}
BStatus: 400, JSON: {"error":{"message":"Missing email","invalidFields":["email"]}}
CStatus: 422, JSON: {"error":"Missing email"}
DStatus: 422, JSON: {"error":{"message":"Missing email","invalidFields":["email"]}}
Attempts:
2 left
💡 Hint
Check the status code set for validation errors and the JSON structure.
🧠 Conceptual
expert
3:00remaining
Which statement about validation error response formatting in Express is true?
Select the correct statement about best practices for formatting validation error responses in Express applications.
AIt is best to send multiple separate responses for each validation error field to keep responses simple.
BValidation error responses should always include a consistent error object with message and details to help clients handle errors properly.
CValidation errors should use HTTP status code 200 with an error field in the JSON to avoid client-side exceptions.
DSending plain text error messages is preferred over JSON for validation errors to reduce response size.
Attempts:
2 left
💡 Hint
Think about how clients consume error responses and what helps them handle errors effectively.

Practice

(1/5)
1. What HTTP status code is typically used to indicate validation errors in an Express API response?
easy
A. 400 Bad Request
B. 200 OK
C. 500 Internal Server Error
D. 404 Not Found

Solution

  1. Step 1: Understand HTTP status codes for client errors

    Validation errors occur when the client sends bad data, so a 4xx code is appropriate.
  2. Step 2: Identify the specific code for bad input

    400 Bad Request is the standard code for invalid input from the client.
  3. Final Answer:

    400 Bad Request -> Option A
  4. Quick Check:

    Validation errors use 400 status [OK]
Hint: Validation errors always use 400 status code [OK]
Common Mistakes:
  • Using 200 OK for validation errors
  • Confusing 500 Internal Server Error with validation errors
  • Using 404 Not Found for input mistakes
2. Which of the following is the correct way to send a JSON validation error response in Express?
easy
A. res.status(400).send('Validation failed')
B. res.json({ error: 'Validation error' })
C. res.status(400).json({ errors: [{ msg: 'Invalid input' }] })
D. res.sendStatus(200)

Solution

  1. Step 1: Use status 400 for validation errors

    The response must have status 400 to indicate a client error.
  2. Step 2: Format the response as JSON with an errors array

    Returning an object with an errors array containing message objects is the standard pattern.
  3. Final Answer:

    res.status(400).json({ errors: [{ msg: 'Invalid input' }] }) -> Option C
  4. Quick Check:

    Use res.status(400).json with errors array [OK]
Hint: Use res.status(400).json({ errors: [...] }) for validation errors [OK]
Common Mistakes:
  • Sending plain text instead of JSON
  • Omitting the status code
  • Using 200 status for errors
3. Given this Express route snippet, what will be the JSON response if the input validation fails?
app.post('/user', (req, res) => {
  const errors = [];
  if (!req.body.email) errors.push({ msg: 'Email is required' });
  if (errors.length > 0) {
    return res.status(400).json({ errors });
  }
  res.send('User created');
});
medium
A. {"error":"Email missing"} with status 400
B. {"errors":[{"msg":"Email is required"}]} with status 400
C. "User created" with status 200
D. Empty response with status 400

Solution

  1. Step 1: Check validation logic for missing email

    If email is missing, an error object with msg 'Email is required' is added to errors array.
  2. Step 2: Return JSON with errors array and status 400

    Since errors array is not empty, the response sends status 400 and JSON containing errors array.
  3. Final Answer:

    {"errors":[{"msg":"Email is required"}]} with status 400 -> Option B
  4. Quick Check:

    Validation fails -> 400 + errors array JSON [OK]
Hint: Errors array with messages sent with 400 status [OK]
Common Mistakes:
  • Returning success message despite errors
  • Wrong JSON key like 'error' instead of 'errors'
  • Not setting status 400
4. Identify the bug in this Express validation error response code:
if (!req.body.name) {
  res.json({ errors: [{ msg: 'Name is required' }] });
  res.status(400);
}
medium
A. Status code must be set before sending response
B. Response should use res.send instead of res.json
C. Errors array should be a string, not an object
D. No bug, code is correct

Solution

  1. Step 1: Check order of status and response methods

    res.status(400) must be called before sending the response to set status properly.
  2. Step 2: Identify that res.json sends response immediately

    Calling res.json first sends the response with default status 200, so status(400) after has no effect.
  3. Final Answer:

    Status code must be set before sending response -> Option A
  4. Quick Check:

    Set status before res.json/send [OK]
Hint: Call res.status before res.json/send [OK]
Common Mistakes:
  • Setting status after sending response
  • Using res.send instead of res.json (not a bug but less clear)
  • Not sending any status code
5. You want to send multiple validation errors in a consistent format in Express. Which code snippet correctly formats and sends these errors with HTTP 400 status?
const errors = [
  { field: 'email', message: 'Invalid email' },
  { field: 'password', message: 'Password too short' }
];
// What is the correct response code?
hard
A. res.status(400).json({ errorMessages: errors })
B. res.json({ errors })
C. res.status(200).json({ errors })
D. res.status(400).json({ errors: errors.map(e => ({ msg: e.message, param: e.field })) })

Solution

  1. Step 1: Map errors to standard format with msg and param keys

    Express validation errors usually have 'msg' for message and 'param' for field name.
  2. Step 2: Send response with status 400 and JSON containing errors array

    Use res.status(400).json(...) to send proper status and formatted errors.
  3. Final Answer:

    res.status(400).json({ errors: errors.map(e => ({ msg: e.message, param: e.field })) }) -> Option D
  4. Quick Check:

    Map errors to {msg, param} and send with 400 status [OK]
Hint: Map errors to {msg, param} and send with status 400 [OK]
Common Mistakes:
  • Sending errors without mapping keys
  • Using 200 status for errors
  • Using wrong JSON key like errorMessages