最近搜索

小程序 异常的使用。

浏览:29
管理员 2025-12-24 18:49

image.png



// 计算房差核心方法(保持不变,仅异常捕获在调用层处理)
calculateRoomDifference(totalPeople, selectedRooms, peoplePerRoom = 2) {
  // 参数验证
  if (totalPeople <= 0 || selectedRooms <= 0 || peoplePerRoom <= 0) {
    throw new Error('参数必须为正数');
  }
  if (selectedRooms * peoplePerRoom < totalPeople) {
    throw new Error('选择的房间数不足以容纳所有人');
  }
  // 计算单人房间数量(需要补房差的房间)
  const singleOccupancyRooms = 2 * selectedRooms - totalPeople;
  // 返回结果(确保不为负数)
  return Math.max(0, singleOccupancyRooms);
},
// 计算房差(增加异常捕获)
calcu_fangcha() {
  try {
    // 尝试执行房差计算
    let fangcha_num = this.calculateRoomDifference(
      this.data.num, 
      this.data.daNum + this.data.shuangNum, 
      2
    );
    console.log(`房差数量是${fangcha_num}`)
    console.log(`房差单价是${this.data.selectDateObj.fangcha}`)
    let flag = false;
    if (fangcha_num > 0) {
      flag = true;
    }
    this.setData({
      fangcha_num: fangcha_num,
      fangcha_flag: flag
    });
  } catch (error) {
    // 捕获异常并弹出提示框
    wx.showToast({
      title: error.message, // 异常信息(参数必须为正数 / 选择的房间数不足以容纳所有人)
      icon: 'none',
      duration: 2000
    });
    // 可选:清空房差相关数据,避免异常状态残留
    this.setData({
      fangcha_num: 0,
      fangcha_flag: false
    });
  }
},


联系站长

站长微信:xiaomao0055

站长QQ:14496453