 | |  |  | 演示 try-catch-finally-throw 语句的复杂用法
- ////🍎交流QQ群711841924群一,苹果内测群,528816639
- // 演示 try-catch-finally-throw 语句的复杂用法
- printl("===== JavaScript 错误处理综合示例开始 =====");
- // 模拟用户数据
- var users = [
- { id: 1, name: "张三", age: 25, email: "zhangsan@example.com" },
- { id: 2, name: "李四", age: 30, email: "lisi@example.com" },
- { id: 3, name: "王五", age: 28, email: "wangwu@example.com" }
- ];
- // 模拟产品数据
- var products = [
- { id: 101, name: "笔记本电脑", price: 5999, stock: 10 },
- { id: 102, name: "智能手机", price: 3999, stock: 50 },
- { id: 103, name: "平板电脑", price: 2999, stock: 25 }
- ];
- // 模拟数据库连接状态
- var dbConnection = null;
- var transactionActive = false;
- // 自定义错误类型
- function ValidationError(message) {
- this.name = "ValidationError";
- this.message = message;
- }
- function DatabaseError(message) {
- this.name = "DatabaseError";
- this.message = message;
- }
- function BusinessError(message) {
- this.name = "BusinessError";
- this.message = message;
- }
- // 模拟数据库连接函数
- function connectDatabase(config) {
- printl("尝试连接数据库...");
-
- // 验证配置参数
- if (!config) {
- throw new ValidationError("数据库配置不能为空");
- }
-
- if (!config.host) {
- throw new ValidationError("数据库主机地址不能为空");
- }
-
- if (!config.database) {
- throw new ValidationError("数据库名称不能为空");
- }
-
- // 模拟数据库连接
- dbConnection = {
- host: config.host,
- database: config.database,
- connected: true,
- connectionTime: new Date().toISOString()
- };
-
- printl("✅ 数据库连接成功: " + dbConnection.host + "/" + dbConnection.database);
- return true;
- }
- // 模拟数据库查询函数
- function queryDatabase(sql) {
- if (!dbConnection || !dbConnection.connected) {
- throw new DatabaseError("数据库未连接,无法执行查询");
- }
-
- if (!sql || typeof sql !== 'string') {
- throw new ValidationError("SQL语句必须为非空字符串");
- }
-
- // 模拟查询结果
- printl("执行SQL查询: " + sql);
- return { rows: [], affectedRows: 0 };
- }
- // 模拟事务开始
- function beginTransaction() {
- if (!dbConnection) {
- throw new DatabaseError("数据库未连接,无法开始事务");
- }
-
- transactionActive = true;
- printl("✅ 事务已开始");
- return true;
- }
- // 模拟事务提交
- function commitTransaction() {
- if (!transactionActive) {
- throw new BusinessError("没有活跃的事务,无法提交");
- }
-
- transactionActive = false;
- printl("✅ 事务已提交");
- return true;
- }
- // 模拟事务回滚
- function rollbackTransaction() {
- if (!transactionActive) {
- printl("⚠️ 没有活跃的事务,无需回滚");
- return false;
- }
-
- transactionActive = false;
- printl("✅ 事务已回滚");
- return true;
- }
- // 模拟关闭数据库连接
- function closeDatabaseConnection() {
- if (dbConnection) {
- printl("关闭数据库连接: " + dbConnection.host + "/" + dbConnection.database);
- dbConnection = null;
- }
- transactionActive = false;
- printl("✅ 数据库连接已关闭");
- }
- // 验证用户输入
- function validateUserInput(data) {
- if (!data) {
- throw new ValidationError("用户数据不能为空");
- }
-
- if (!data.name || data.name.trim() === "") {
- throw new ValidationError("用户名不能为空");
- }
-
- if (data.name.length < 2 || data.name.length > 20) {
- throw new ValidationError("用户名长度必须在2-20个字符之间");
- }
-
- if (!data.email || data.email.indexOf('@') === -1) {
- throw new ValidationError("邮箱格式不正确");
- }
-
- if (data.age !== undefined) {
- if (typeof data.age !== 'number' || data.age < 0 || data.age > 150) {
- throw new ValidationError("年龄必须是0-150之间的数字");
- }
- }
-
- return true;
- }
- // 验证产品数据
- function validateProductData(product) {
- if (!product) {
- throw new ValidationError("产品数据不能为空");
- }
-
- if (!product.name || product.name.trim() === "") {
- throw new ValidationError("产品名称不能为空");
- }
-
- if (typeof product.price !== 'number' || product.price < 0) {
- throw new ValidationError("产品价格必须为非负数");
- }
-
- if (typeof product.stock !== 'number' || product.stock < 0) {
- throw new ValidationError("产品库存必须为非负数");
- }
-
- return true;
- }
- // 处理用户注册(包含完整错误处理流程)
- function processUserRegistration(userData) {
- printl("========== 处理用户注册 ==========");
- printl("用户数据: " + JSON.stringify(userData));
-
- var result = { success: false, message: "", userId: null };
-
- try {
- // 步骤1: 验证用户输入
- printl("步骤1: 验证用户输入");
- validateUserInput(userData);
- printl("✅ 用户输入验证通过");
-
- // 步骤2: 连接数据库
- printl("步骤2: 连接数据库");
- connectDatabase({
- host: "localhost",
- database: "userdb",
- username: "admin"
- });
-
- // 步骤3: 开始事务
- printl("步骤3: 开始事务");
- beginTransaction();
-
- // 步骤4: 插入用户数据
- printl("步骤4: 插入用户数据到数据库");
- var sql = "INSERT INTO users (name, email, age) VALUES ('" +
- userData.name + "', '" + userData.email + "', " +
- (userData.age || 0) + ")";
- queryDatabase(sql);
-
- // 步骤5: 模拟生成用户ID
- var newUserId = users.length + 1;
- printl("✅ 新用户ID: " + newUserId);
-
- // 步骤6: 提交事务
- printl("步骤6: 提交事务");
- commitTransaction();
-
- result.success = true;
- result.message = "用户注册成功";
- result.userId = newUserId;
-
- } catch (e) {
- printl("❌ 发生错误: " + e.name + " - " + e.message);
-
- // 记录错误日志
- result.message = e.name + ": " + e.message;
-
- // 如果有活跃的事务,进行回滚
- if (transactionActive) {
- printl("执行事务回滚...");
- rollbackTransaction();
- }
-
- // 根据错误类型进行不同的处理
- if (e instanceof ValidationError) {
- result.message = "数据验证失败: " + e.message;
- } else if (e instanceof DatabaseError) {
- result.message = "数据库操作失败: " + e.message;
- } else {
- result.message = "未知错误: " + e.message;
- }
-
- } finally {
- printl("========== 执行清理操作 ==========");
- // 无论成功与否,都关闭数据库连接
- closeDatabaseConnection();
- printl("✅ 注册流程处理完成");
- }
-
- printl("注册结果: " + JSON.stringify(result));
- return result;
- }
- // 处理产品创建(演示不同的错误场景)
- function processProductCreation(productData) {
- printl("========== 处理产品创建 ==========");
- printl("产品数据: " + JSON.stringify(productData));
-
- var result = { success: false, message: "" };
-
- try {
- // 验证产品数据
- printl("验证产品数据");
- validateProductData(productData);
- printl("✅ 产品数据验证通过");
-
- // 连接数据库
- printl("连接数据库");
- connectDatabase({
- host: "localhost",
- database: "productdb"
- });
-
- // 检查库存是否足够
- if (productData.stock < 10) {
- throw new BusinessError("产品库存不足,最低需要10件");
- }
-
- // 执行产品创建逻辑
- var newProductId = products.length + 101;
- products.push({
- id: newProductId,
- name: productData.name,
- price: productData.price,
- stock: productData.stock
- });
-
- printl("✅ 产品创建成功,ID: " + newProductId);
- result.success = true;
- result.message = "产品创建成功,ID: " + newProductId;
-
- } catch (e) {
- printl("❌ 发生错误: " + e.message);
- result.message = e.message;
-
- // 业务逻辑错误不一定会回滚事务
- if (!(e instanceof BusinessError)) {
- rollbackTransaction();
- }
-
- } finally {
- printl("清理数据库连接");
- closeDatabaseConnection();
- }
-
- printl("创建结果: " + JSON.stringify(result));
- return result;
- }
- // 演示嵌套的try-catch结构
- function complexCalculation(a, b, operation) {
- printl("========== 复杂计算演示 ==========");
- printl("参数: a=" + a + ", b=" + b + ", operation=" + operation);
-
- var result = { value: null, error: null };
-
- try {
- // 外层try-catch处理参数验证
- try {
- if (typeof a !== 'number' || typeof b !== 'number') {
- throw new ValidationError("参数必须是数字");
- }
-
- if (a < 0 || b < 0) {
- throw new ValidationError("参数不能为负数");
- }
-
- printl("参数验证通过");
-
- } catch (innerError) {
- printl("内层验证错误: " + innerError.message);
- // 重新抛出错误,在外层处理
- throw innerError;
- }
-
- // 执行计算
- switch (operation) {
- case 'add':
- result.value = a + b;
- break;
- case 'subtract':
- result.value = a - b;
- break;
- case 'multiply':
- result.value = a * b;
- break;
- case 'divide':
- if (b === 0) {
- throw new BusinessError("除数不能为零");
- }
- result.value = a / b;
- break;
- case 'power':
- if (b > 10) {
- throw new BusinessError("指数不能超过10,以防止数值溢出");
- }
- result.value = Math.pow(a, b);
- break;
- default:
- throw new ValidationError("不支持的运算: " + operation);
- }
-
- printl("计算结果: " + result.value);
-
- } catch (e) {
- printl("❌ 计算错误: " + e.message);
- result.error = e.message;
- } finally {
- printl("✅ 计算流程结束");
- }
-
- return result;
- }
- // 主程序入口
- function main() {
- printl("========================================");
- printl(" JavaScript 错误处理主程序开始 ");
- printl("========================================");
-
- var executionLog = [];
-
- // 测试场景1: 成功的用户注册
- executionLog.push("测试场景1: 成功注册用户");
- var user1 = { name: "赵六", email: "zhaoliu@example.com", age: 35 };
- var regResult1 = processUserRegistration(user1);
- printl("注册结果: " + (regResult1.success ? "成功" : "失败") + " - " + regResult1.message);
-
- // 测试场景2: 失败的用户注册(邮箱格式错误)
- executionLog.push("测试场景2: 邮箱格式错误");
- var user2 = { name: "孙七", email: "invalid-email", age: 40 };
- var regResult2 = processUserRegistration(user2);
- printl("注册结果: " + (regResult2.success ? "成功" : "失败") + " - " + regResult2.message);
-
- // 测试场景3: 失败的产品创建(库存不足)
- executionLog.push("测试场景3: 库存不足");
- var product1 = { name: "智能手表", price: 1999, stock: 5 };
- var prodResult1 = processProductCreation(product1);
- printl("创建结果: " + (prodResult1.success ? "成功" : "失败") + " - " + prodResult1.message);
-
- // 测试场景4: 成功的产品创建
- executionLog.push("测试场景4: 成功创建产品");
- var product2 = { name: "无线耳机", price: 599, stock: 100 };
- var prodResult2 = processProductCreation(product2);
- printl("创建结果: " + (prodResult2.success ? "成功" : "失败") + " - " + prodResult2.message);
-
- // 测试场景5: 复杂计算
- executionLog.push("测试场景5: 复杂计算");
- var calcResult1 = complexCalculation(5, 3, 'power');
- var calcResult2 = complexCalculation(10, 0, 'divide');
- var calcResult3 = complexCalculation(7, 2, 'multiply');
- var calcResult4 = complexCalculation(15, 11, 'power'); // 指数超过10
-
- // 测试场景6: 验证错误传播
- executionLog.push("测试场景6: 错误传播");
- try {
- try {
- throw new DatabaseError("模拟数据库连接失败");
- } catch (innerError) {
- printl("捕获到内部错误: " + innerError.message);
- // 添加额外信息后重新抛出
- throw new DatabaseError(innerError.message + " (错误代码: DB_CONN_001)");
- }
- } catch (outerError) {
- printl("在外层捕获到错误: " + outerError.message);
- printl("错误类型: " + outerError.name);
- }
-
- // 总结
- printl("========================================");
- printl(" 执行总结");
- printl("========================================");
- printl("总共执行测试场景: " + executionLog.length + " 个");
- for (var i = 0; i < executionLog.length; i++) {
- printl(" " + (i + 1) + ". " + executionLog[i]);
- }
- printl("✅ 所有测试场景执行完毕");
- printl("========================================");
- }
- // 执行主程序
- main();
- printl("===== JavaScript 错误处理综合示例结束 =====");
复制代码
| |  | |  |
|