 | |  |  | JavaScript 高级错误处理实战示例
- /**
- * ============================================
- * JavaScript 高级错误处理实战示例
- * 演示企业级应用中的完整错误处理机制
- * 包含:自定义错误类、异步操作、数据验证、事务管理等
- * 交流QQ群: 711841924 (群一) / 528816639 (安卓内测群)
- * err
- * ============================================
- */
- // ==================== 自定义错误类定义 ====================
- // 基础应用错误类
- function AppError(message, code) {
- this.name = "AppError";
- this.message = message;
- this.code = code || "UNKNOWN_ERROR";
- this.timestamp = new Date().toISOString();
- }
- // 用户相关错误
- function UserError(message, code) {
- this.name = "UserError";
- this.message = message;
- this.code = code || "USER_ERROR";
- this.timestamp = new Date().toISOString();
- }
- // 数据库相关错误
- function DatabaseError(message, code) {
- this.name = "DatabaseError";
- this.message = message;
- this.code = code || "DB_ERROR";
- this.timestamp = new Date().toISOString();
- }
- // 业务逻辑错误
- function BusinessError(message, code) {
- this.name = "BusinessError";
- this.message = message;
- this.code = code || "BUSINESS_ERROR";
- this.timestamp = new Date().toISOString();
- }
- // 网络请求错误
- function NetworkError(message, code) {
- this.name = "NetworkError";
- this.message = message;
- this.code = code || "NETWORK_ERROR";
- this.timestamp = new Date().toISOString();
- }
- // ==================== 模拟数据存储 ====================
- var mockDatabase = {
- users: [
- { id: 1, username: "admin", email: "admin@example.com", role: "admin", status: "active" },
- { id: 2, username: "user1", email: "user1@example.com", role: "user", status: "active" },
- { id: 3, username: "user2", email: "user2@example.com", role: "user", status: "inactive" }
- ],
- products: [
- { id: 101, name: "笔记本电脑", price: 5999, stock: 10, category: "electronics" },
- { id: 102, name: "智能手机", price: 3999, stock: 50, category: "electronics" },
- { id: 103, name: "办公椅", price: 899, stock: 25, category: "furniture" }
- ],
- orders: []
- };
- // ==================== 工具函数 ====================
- // 日志记录器
- function Logger(level, message, context) {
- var timestamp = new Date().toISOString();
- var logEntry = "[" + timestamp + "] [" + level + "] " + message;
-
- if (context) {
- logEntry += " | Context: " + JSON.stringify(context);
- }
-
- switch(level.toUpperCase()) {
- case "ERROR":
- printl("❌ " + logEntry);
- break;
- case "WARN":
- printl("⚠️ " + logEntry);
- break;
- case "INFO":
- printl("ℹ️ " + logEntry);
- break;
- case "DEBUG":
- printl("🔍 " + logEntry);
- break;
- default:
- printl(logEntry);
- }
- }
- // 输入验证器
- function Validator() {
- this.errors = [];
- }
- Validator.prototype.validateEmail = function(email) {
- if (!email || typeof email !== 'string') {
- throw new UserError("邮箱地址不能为空", "EMAIL_REQUIRED");
- }
-
- if (email.indexOf('@') === -1 || email.indexOf('.') === -1) {
- throw new UserError("邮箱格式不正确", "INVALID_EMAIL_FORMAT");
- }
-
- return true;
- };
- Validator.prototype.validateUsername = function(username) {
- if (!username || typeof username !== 'string') {
- throw new UserError("用户名不能为空", "USERNAME_REQUIRED");
- }
-
- if (username.length < 3 || username.length > 20) {
- throw new UserError("用户名长度必须在3-20个字符之间", "INVALID_USERNAME_LENGTH");
- }
-
- if (!/^[a-zA-Z0-9_]+$/.test(username)) {
- throw new UserError("用户名只能包含字母、数字和下划线", "INVALID_USERNAME_CHARS");
- }
-
- return true;
- };
- Validator.prototype.validatePassword = function(password) {
- if (!password || typeof password !== 'string') {
- throw new UserError("密码不能为空", "PASSWORD_REQUIRED");
- }
-
- if (password.length < 6) {
- throw new UserError("密码长度至少为6个字符", "PASSWORD_TOO_SHORT");
- }
-
- if (!/[A-Z]/.test(password)) {
- throw new UserError("密码必须包含至少一个大写字母", "PASSWORD_NO_UPPERCASE");
- }
-
- if (!/[0-9]/.test(password)) {
- throw new UserError("密码必须包含至少一个数字", "PASSWORD_NO_NUMBER");
- }
-
- return true;
- };
- Validator.prototype.validateProductData = function(product) {
- if (!product) {
- throw new BusinessError("产品数据不能为空", "PRODUCT_DATA_REQUIRED");
- }
-
- if (!product.name || product.name.trim() === "") {
- throw new BusinessError("产品名称不能为空", "PRODUCT_NAME_REQUIRED");
- }
-
- if (typeof product.price !== 'number' || product.price <= 0) {
- throw new BusinessError("产品价格必须为正数", "INVALID_PRODUCT_PRICE");
- }
-
- if (typeof product.stock !== 'number' || product.stock < 0) {
- throw new BusinessError("产品库存不能为负数", "INVALID_PRODUCT_STOCK");
- }
-
- return true;
- };
- // ==================== 核心业务函数 ====================
- // 用户注册功能(包含完整错误处理)
- function registerUser(userData) {
- Logger("INFO", "开始用户注册流程", { username: userData.username });
-
- var result = { success: false, userId: null, message: "" };
- var validator = new Validator();
-
- try {
- // 步骤1: 验证输入数据
- Logger("DEBUG", "执行输入验证");
- validator.validateUsername(userData.username);
- validator.validateEmail(userData.email);
- validator.validatePassword(userData.password);
-
- Logger("INFO", "输入验证通过");
-
- // 步骤2: 检查用户是否已存在
- Logger("DEBUG", "检查用户是否存在");
- var existingUser = mockDatabase.users.find(function(u) {
- return u.username === userData.username;
- });
-
- if (existingUser) {
- throw new UserError("用户名已存在", "USERNAME_EXISTS");
- }
-
- // 步骤3: 创建新用户
- Logger("DEBUG", "创建新用户记录");
- var newUser = {
- id: mockDatabase.users.length + 1,
- username: userData.username,
- email: userData.email,
- role: "user",
- status: "active",
- createdAt: new Date().toISOString()
- };
-
- mockDatabase.users.push(newUser);
-
- result.success = true;
- result.userId = newUser.id;
- result.message = "用户注册成功";
-
- Logger("INFO", "用户注册成功", { userId: newUser.id });
-
- } catch (error) {
- Logger("err", "用户注册失败", { error: error.message, code: error.code });
-
- result.message = error.message;
- result.errorCode = error.code;
-
- // 根据错误类型进行特殊处理
- if (error instanceof UserError) {
- Logger("WARN", "用户输入验证失败");
- } else if (error instanceof BusinessError) {
- Logger("WARN", "业务逻辑错误");
- } else {
- Logger("err", "未知系统错误");
- }
-
- } finally {
- Logger("DEBUG", "用户注册流程结束");
- }
-
- return result;
- }
- // 订单处理功能(演示事务管理)
- function processOrder(orderData) {
- Logger("INFO", "开始处理订单", { productId: orderData.productId, quantity: orderData.quantity });
-
- var result = { success: false, orderId: null, message: "" };
- var transactionStarted = false;
-
- try {
- // 步骤1: 验证订单数据
- Logger("DEBUG", "验证订单数据");
- if (!orderData.productId || !orderData.quantity) {
- throw new BusinessError("订单数据不完整", "INCOMPLETE_ORDER_DATA");
- }
-
- if (orderData.quantity <= 0) {
- throw new BusinessError("订购数量必须大于0", "INVALID_QUANTITY");
- }
-
- // 步骤2: 查找产品
- Logger("DEBUG", "查找产品信息");
- var product = mockDatabase.products.find(function(p) {
- return p.id === orderData.productId;
- });
-
- if (!product) {
- throw new BusinessError("产品不存在", "PRODUCT_NOT_FOUND");
- }
-
- // 步骤3: 检查库存
- Logger("DEBUG", "检查产品库存");
- if (product.stock < orderData.quantity) {
- throw new BusinessError("库存不足,当前库存: " + product.stock, "INSUFFICIENT_STOCK");
- }
-
- // 步骤4: 开始事务(模拟)
- Logger("DEBUG", "开始订单事务");
- transactionStarted = true;
-
- // 步骤5: 更新库存
- Logger("DEBUG", "更新产品库存");
- product.stock -= orderData.quantity;
-
- // 步骤6: 创建订单记录
- Logger("DEBUG", "创建订单记录");
- var newOrder = {
- id: mockDatabase.orders.length + 1,
- productId: orderData.productId,
- productName: product.name,
- quantity: orderData.quantity,
- totalPrice: product.price * orderData.quantity,
- status: "confirmed",
- createdAt: new Date().toISOString()
- };
-
- mockDatabase.orders.push(newOrder);
-
- // 步骤7: 提交事务
- Logger("DEBUG", "提交订单事务");
- transactionStarted = false;
-
- result.success = true;
- result.orderId = newOrder.id;
- result.message = "订单处理成功";
-
- Logger("INFO", "订单处理成功", { orderId: newOrder.id, total: newOrder.totalPrice });
-
- } catch (error) {
- Logger("err", "订单处理失败", { error: error.message, code: error.code });
-
- result.message = error.message;
- result.errorCode = error.code;
-
- // 如果事务已开始,则回滚
- if (transactionStarted) {
- Logger("WARN", "执行事务回滚");
- // 在实际应用中这里会恢复库存等状态
- transactionStarted = false;
- }
-
- } finally {
- Logger("DEBUG", "订单处理流程结束");
- }
-
- return result;
- }
- // 数据查询功能(演示多种查询场景)
- function queryData(queryType, filters) {
- Logger("INFO", "执行数据查询", { type: queryType, filters: filters });
-
- var result = { success: false, data: [], count: 0, message: "" };
-
- try {
- // 参数验证
- if (!queryType) {
- throw new AppError("查询类型不能为空", "QUERY_TYPE_REQUIRED");
- }
-
- switch (queryType.toLowerCase()) {
- case "users":
- Logger("DEBUG", "查询用户数据");
-
- if (filters && filters.role) {
- result.data = mockDatabase.users.filter(function(u) {
- return u.role === filters.role;
- });
- } else {
- result.data = mockDatabase.users.slice(); // 返回副本
- }
- break;
-
- case "products":
- Logger("DEBUG", "查询产品数据");
-
- if (filters && filters.category) {
- result.data = mockDatabase.products.filter(function(p) {
- return p.category === filters.category;
- });
- } else if (filters && filters.minPrice) {
- result.data = mockDatabase.products.filter(function(p) {
- return p.price >= filters.minPrice;
- });
- } else {
- result.data = mockDatabase.products.slice();
- }
- break;
-
- case "orders":
- Logger("DEBUG", "查询订单数据");
-
- if (filters && filters.status) {
- result.data = mockDatabase.orders.filter(function(o) {
- return o.status === filters.status;
- });
- } else {
- result.data = mockDatabase.orders.slice();
- }
- break;
-
- default:
- throw new AppError("不支持的查询类型: " + queryType, "UNSUPPORTED_QUERY_TYPE");
- }
-
- result.count = result.data.length;
- result.success = true;
- result.message = "查询成功,返回 " + result.count + " 条记录";
-
- Logger("INFO", "数据查询成功", { count: result.count });
-
- } catch (error) {
- Logger("err", "数据查询失败", { error: error.message, code: error.code });
-
- result.message = error.message;
- result.errorCode = error.code;
-
- } finally {
- Logger("DEBUG", "数据查询流程结束");
- }
-
- return result;
- }
- // 批量操作功能(演示复杂的错误处理)
- function batchProcess(items, operation) {
- Logger("INFO", "开始批量操作", { itemCount: items.length, operation: operation });
-
- var results = {
- successful: [],
- failed: [],
- summary: {}
- };
-
- try {
- for (var i = 0; i < items.length; i++) {
- var item = items[i];
- var itemResult = { index: i, item: item, success: false, error: null };
-
- try {
- // 对每个项目执行操作
- switch (operation) {
- case "validate":
- // 验证操作
- if (!item || typeof item !== 'object') {
- throw new AppError("无效的项目数据", "INVALID_ITEM");
- }
- itemResult.success = true;
- break;
-
- case "transform":
- // 转换操作
- if (!item.name) {
- throw new AppError("项目缺少名称字段", "MISSING_NAME_FIELD");
- }
- item.transformed = item.name.toUpperCase();
- itemResult.success = true;
- break;
-
- case "process":
- // 处理操作(模拟)
- if (Math.random() > 0.8) { // 20%概率失败
- throw new AppError("随机处理失败", "RANDOM_FAILURE");
- }
- itemResult.success = true;
- break;
-
- default:
- throw new AppError("不支持的操作类型: " + operation, "UNSUPPORTED_OPERATION");
- }
-
- results.successful.push(itemResult);
-
- } catch (itemError) {
- Logger("WARN", "批量操作中单个项目失败", {
- index: i,
- error: itemError.message
- });
-
- itemResult.error = itemError.message;
- results.failed.push(itemResult);
- }
- }
-
- // 生成摘要
- results.summary = {
- total: items.length,
- successful: results.successful.length,
- failed: results.failed.length,
- successRate: Math.round((results.successful.length / items.length) * 100) + "%"
- };
-
- Logger("INFO", "批量操作完成", results.summary);
-
- } catch (batchError) {
- Logger("err", "批量操作整体失败", { error: batchError.message });
- throw batchError; // 重新抛出严重错误
-
- } finally {
- Logger("DEBUG", "批量操作流程结束");
- }
-
- return results;
- }
- // ==================== 测试用例 ====================
- function runTests() {
- Logger("INFO", "========== 开始运行测试用例 ==========");
-
- // 测试1: 成功的用户注册
- Logger("INFO", "--- 测试1: 成功用户注册 ---");
- var testUser1 = {
- username: "newuser1",
- email: "newuser1@example.com",
- password: "Password123"
- };
- var regResult1 = registerUser(testUser1);
- printl("测试结果: " + (regResult1.success ? "✅ 通过" : "❌ 失败"));
- sleep.second(2);
-
- // 测试2: 失败的用户注册(用户名太短)
- Logger("INFO", "--- 测试2: 用户名太短 ---");
- var testUser2 = {
- username: "ab",
- email: "short@example.com",
- password: "Password123"
- };
- var regResult2 = registerUser(testUser2);
- printl("测试结果: " + (!regResult2.success ? "✅ 通过" : "❌ 失败"));
- sleep.second(2);
-
- // 测试3: 失败的用户注册(邮箱格式错误)
- Logger("INFO", "--- 测试3: 邮箱格式错误 ---");
- var testUser3 = {
- username: "validuser",
- email: "invalid-email",
- password: "Password123"
- };
- var regResult3 = registerUser(testUser3);
- printl("测试结果: " + (!regResult3.success ? "✅ 通过" : "❌ 失败"));
- sleep.second(2);
-
- // 测试4: 成功的订单处理
- Logger("INFO", "--- 测试4: 成功订单处理 ---");
- var testOrder1 = {
- productId: 101,
- quantity: 2
- };
- var orderResult1 = processOrder(testOrder1);
- printl("测试结果: " + (orderResult1.success ? "✅ 通过" : "❌ 失败"));
- sleep.second(2);
-
- // 测试5: 失败的订单处理(库存不足)
- Logger("INFO", "--- 测试5: 库存不足 ---");
- var testOrder2 = {
- productId: 101,
- quantity: 100 // 超过库存
- };
- var orderResult2 = processOrder(testOrder2);
- printl("测试结果: " + (!orderResult2.success ? "✅ 通过" : "❌ 失败"));
- sleep.second(2);
-
- // 测试6: 数据查询
- Logger("INFO", "--- 测试6: 查询活跃用户 ---");
- var queryResult1 = queryData("users", { role: "user" });
- printl("查询结果: " + (queryResult1.success ? "✅ 通过" : "❌ 失败") +
- ", 找到 " + queryResult1.count + " 条记录");
- sleep.second(2);
-
- // 测试7: 批量处理
- Logger("INFO", "--- 测试7: 批量验证操作 ---");
- var batchItems = [
- { name: "Item1", value: 100 },
- { name: "Item2", value: 200 },
- { invalid: true }, // 无效项
- { name: "Item3", value: 300 }
- ];
- var batchResult = batchProcess(batchItems, "validate");
- printl("批量处理结果: 成功 " + batchResult.summary.successful +
- " 个, 失败 " + batchResult.summary.failed + " 个");
- sleep.second(2);
-
- Logger("INFO", "========== 测试用例执行完毕 ==========");
- }
- // ==================== 主程序入口 ====================
- function main() {
- Logger("INFO", "========================================");
- Logger("INFO", " JavaScript 高级错误处理实战示例 ");
- Logger("INFO", "========================================");
-
- try {
- // 运行所有测试
- runTests();
-
- // 显示最终统计
- Logger("INFO", "========================================");
- Logger("INFO", " 执行总结");
- Logger("INFO", "========================================");
- Logger("INFO", "总用户数: " + mockDatabase.users.length);
- Logger("INFO", "总产品数: " + mockDatabase.products.length);
- Logger("INFO", "总订单数: " + mockDatabase.orders.length);
- Logger("INFO", "✅ 示例程序执行完成");
-
- } catch (criticalError) {
- Logger("err", "程序发生严重错误", {
- error: criticalError.message,
- stack: criticalError.stack || "无堆栈信息"
- });
-
- } finally {
- Logger("INFO", "========================================");
- Logger("INFO", " 程序执行结束");
- Logger("INFO", "========================================");
- printl("===== JavaScript 高级错误处理实战示例结束 =====");
- printl("========== 脚本执行完毕 ==========");
- }
- }
- // 启动主程序
- main();
复制代码
| |  | |  |
|