You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理API无效semesterId/classId/dayofWeek输入避免后端崩溃

Hey there! Let's fix your API to handle invalid inputs gracefully and avoid backend crashes. Here's a step-by-step solution tailored to your code:

Step 1: Add Input Validation Up Front

First, we need to check if the incoming parameters are valid before even hitting the database. This prevents unnecessary database calls and gives clear feedback to the client.

Step 2: Return Clear Error Responses

When invalid inputs are detected, send a 400 Bad Request status code with specific details about what's wrong. For database errors, we'll hide internal details but still inform the client something went wrong.

Modified Code with Validation & Error Handling
app.get('/basic/result', function (req, res, next) {
  const { classId, semesterId, dayofWeek } = req.query;
  const validationErrors = [];

  // Validate semesterId: Check for presence, numeric type, and expected format (e.g., 10-digit string)
  if (!semesterId || isNaN(semesterId) || semesterId.length !== 10) {
    validationErrors.push("semesterId must be a 10-digit numeric string (e.g., 2020100001)");
  }

  // Validate classId: Same format check as semesterId
  if (!classId || isNaN(classId) || classId.length !== 10) {
    validationErrors.push("classId must be a 10-digit numeric string (e.g., 4110000001)");
  }

  // Validate dayofWeek: Must be an integer between 1-7 (since weeks have 7 days)
  const parsedDay = parseInt(dayofWeek, 10);
  if (!dayofWeek || isNaN(parsedDay) || parsedDay < 1 || parsedDay > 7) {
    validationErrors.push("dayofWeek must be an integer between 1 and 7");
  }

  // If any validation fails, return 400 with error details
  if (validationErrors.length > 0) {
    return res.status(400).json({
      status: "error",
      message: "Invalid input parameters",
      errors: validationErrors
    });
  }

  // Proceed with database call only if inputs are valid
  database.getDayLecture(classId, semesterId, parsedDay, (error, result) => {
    if (error) {
      // Log the error for your debugging (don't expose this to the client)
      console.error("Database fetch failed:", error);
      // Return a generic server error response
      return res.status(500).json({
        status: "error",
        message: "Failed to retrieve lecture data. Please try again later."
      });
    }

    const sortResult = backend.minHalls(result);
    return res.json({ status: "success", result: sortResult });
  });
});
Key Improvements Explained
  • Input Validation: We check each parameter for existence, correct type, and expected format. For dayofWeek, we parse it to an integer first to ensure it's a valid number before checking the 1-7 range.
  • User-Friendly Errors: Instead of letting the backend crash or return a vague error, we tell the client exactly which parameter is wrong and what the valid format is.
  • Secure Database Error Handling: We log internal database errors for debugging but return a generic message to the client—this prevents exposing sensitive backend details.
Bonus: Optional Enhancements
  • Use Validation Libraries: For more complex validation (like regex patterns for IDs), libraries like Joi or Yup can simplify your code and make it more maintainable.
  • Global Error Middleware: If you have multiple routes, set up a global error handler to standardize error responses across your API:
    app.use((err, req, res, next) => {
      console.error("Unhandled error:", err);
      res.status(err.statusCode || 500).json({
        status: "error",
        message: err.message || "Internal server error"
      });
    });
    

内容的提问来源于stack exchange,提问作者wink

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:37:51