Homework & Coding Practice

Homework/Practice Coding Assignment (20-min)

Task: Add a Custom Error Handler for Invalid JSON Payloads

Step-by-Step Procedure:

  1. 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);
      });
  2. Step 2: Simulate an Invalid JSON Payload:

    • Use Postman to send a POST request to /tasks with malformed JSON:

      json코드 복사{ "title": "Invalid JSON"
  3. Step 3: Observe the Response:

    • Verify the custom error message:

      json코드 복사{ "error": "Invalid JSON payload" }
  4. 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

  1. Students learn to handle dynamic routes and process JSON data in Express.

  2. Students gain hands-on experience in building and testing a REST API.

  3. Homework reinforces skills in creating custom error handlers and handling invalid inputs.

Last updated