Concept Flow - Validation error response formatting
Receive HTTP Request
Validate Input Data
Process Request
Send Success
End
The server receives a request, checks the input data, and either processes it or sends back a formatted error response.
Jump into concepts and practice - no test required
app.post('/user', (req, res) => { const { name, age } = req.body; if (!name) { return res.status(400).json({ error: 'Name is required' }); } res.json({ message: 'User created' }); });
| Step | Action | Input Data | Validation Result | Response Sent |
|---|---|---|---|---|
| 1 | Receive request | { age: 25 } | Not validated yet | No response yet |
| 2 | Check if name exists | { age: 25 } | Name missing | 400 status with { error: 'Name is required' } |
| 3 | Stop processing | N/A | Validation failed | Error response sent, request ended |
| Variable | Start | After Step 2 | Final |
|---|---|---|---|
| req.body.name | undefined | undefined | undefined |
| validationResult | undefined | false (name missing) | false (validation failed) |
| response.statusCode | undefined | 400 | 400 |
Validation error response formatting in Express:
- Receive request and extract input
- Check required fields (e.g., name)
- If missing, send res.status(400).json({ error: 'message' })
- Stop further processing
- If valid, continue and send success responseapp.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');
});if (!req.body.name) {
res.json({ errors: [{ msg: 'Name is required' }] });
res.status(400);
}const errors = [
{ field: 'email', message: 'Invalid email' },
{ field: 'password', message: 'Password too short' }
];
// What is the correct response code?