مدیریت خطاها در Node.js

برنامه‌های نوشته‌شده با Node.js در طول اجرا با انواع مختلف خطاها مواجه می‌شوند؛ از خطاهای استاندارد جاوااسکریپت گرفته تا خطاهای سیستم‌عامل و خطاهای تعریف‌شده توسط کاربر. Node.js مکانیزم‌های مختلفی برای انتشار و مدیریت این خطاها ارائه می‌دهد. شناخت این مکانیزم‌ها برای نوشتن برنامه‌های پایدار و مقاوم ضروری است.

Standard JavaScript ErrorsSystem ErrorsAssertionErrorError propagationEventEmitter error events

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۶ دی ۱۴۰۴

1. دسته‌بندی خطاها


  • خطاهای استاندارد جاوااسکریپت: مانند SyntaxError، ReferenceError، TypeError.
  • DOMException: خطاهای استاندارد مرورگر.
  • خطاهای سیستم: ناشی از محدودیت‌های سیستم‌عامل (مثلاً تلاش برای باز کردن فایل غیر موجود).
  • AssertionError: خطاهای منطقی غیرمنتظره که توسط ماژول assert ایجاد می‌شوند.
  • خطاهای تعریف‌شده توسط کاربر: خطاهایی که در کد برنامه ایجاد می‌شوند.

2. انتشار و مدیریت خطاها


نحوهٔ انتشار خطاها به نوع API بستگی دارد:


  • APIهای همزمان: خطاها را با throw منتشر می‌کنند و باید با try...catch مدیریت شوند.
  • APIهای غیرهمزمان مبتنی بر Promise: خطاها با reject منتشر می‌شوند و باید با catch مدیریت شوند.
  • APIهای غیرهمزمان مبتنی بر Callback: خطاها به‌عنوان آرگومان اول Callback ارسال می‌شوند.
  • EventEmitterها: خطاها از طریق رویداد 'error' منتشر می‌شوند.

3. نمونه‌ها


// همزمان
try {
  const m = 1;
  const n = m + z; // ReferenceError
} catch (err) {
  console.error(err);
}

// غیرهمزمان با Promise
const fs = require('node:fs/promises');
(async () => {
  try {
    await fs.readFile('file.txt');
  } catch (err) {
    console.error('Error reading file!', err);
  }
})();

// غیرهمزمان با Callback
const fs = require('node:fs');
fs.readFile('file.txt', (err, data) => {
  if (err) {
    console.error('Error reading file!', err);
    return;
  }
});

4. ویژگی‌های کلاس Error


  • error.message: توضیح متنی خطا.
  • error.code: کد خطا برای شناسایی پایدار.
  • error.stack: مسیر اجرای کد هنگام ایجاد خطا.
  • error.cause: علت اصلی خطا (از نسخه 16.9.0).

5. انواع خطاهای مهم


  • AssertionError: شکست در اعتبارسنجی منطقی.
  • RangeError: آرگومان خارج از محدودهٔ معتبر.
  • ReferenceError: دسترسی به متغیر تعریف‌نشده.
  • SyntaxError: کد نامعتبر جاوااسکریپت.
  • SystemError: خطاهای ناشی از محدودیت‌های سیستم‌عامل.

نتیجه‌گیری


مدیریت صحیح خطاها در Node.js برای ساخت برنامه‌های پایدار و مقاوم حیاتی است. توسعه‌دهندگان باید با انواع خطاها و مکانیزم‌های انتشار آن‌ها آشنا باشند و از ابزارهایی مانند try...catch، Promise.catch، و رویداد 'error' در EventEmitterها برای مدیریت مناسب استفاده کنند.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

ادامه

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

ادامه

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

ادامه

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

ادامه

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

ادامه

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

ادامه