Homework & Coding Practice
Homework/Practice Coding Assignment (20-min)
Task: Add a Custom Error Handler for Invalid JSON Payloads
Step-by-Step Procedure:
Step 1: Define the Custom Error Handler:
Add the following middleware to
app.js:javascript코드 복사app.use((err, req, res, next) => { if (err instanceof SyntaxError && err.status === 400 && 'body' in err) { return res.status(400).json({ error: 'Invalid JSON payload' }); } next(err); });
Step 2: Simulate an Invalid JSON Payload:
Use Postman to send a POST request to
/taskswith malformed JSON:json코드 복사{ "title": "Invalid JSON"
Step 3: Observe the Response:
Verify the custom error message:
json코드 복사{ "error": "Invalid JSON payload" }
Step 4: Handle Other Errors:
Add a fallback error handler for unexpected issues:
javascript코드 복사app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Internal Server Error'); });
Expected Outcomes
Students learn to handle dynamic routes and process JSON data in Express.
Students gain hands-on experience in building and testing a REST API.
Homework reinforces skills in creating custom error handlers and handling invalid inputs.
Last updated