Now.js Framework Documentation

Now.js Framework Documentation

ErrorManager

TH 15 Dec 2025 08:52

ErrorManager

ภาพรวม

ErrorManager คือระบบจัดการ errors แบบ centralized ใน Now.js Framework รองรับ logging, notifications และ event dispatching

ใช้เมื่อ:

  • ต้องการจัดการ errors แบบรวมศูนย์
  • ต้องการ log errors อย่างสม่ำเสมอ
  • ต้องการ notify ผู้ใช้เมื่อเกิด error
  • ต้องการ dispatch events เมื่อเกิด error

ทำไมต้องใช้:

  • ✅ Centralized error handling
  • ✅ Consistent logging format
  • ✅ User notifications
  • ✅ Event dispatching
  • ✅ Debug mode support
  • ✅ Error normalization

การใช้งานพื้นฐาน

Initialization

ErrorManager.init({
  debug: true,
  notificationDuration: 5000
});

Handle Error

try {
  await riskyOperation();
} catch (error) {
  ErrorManager.handle(error, {
    context: 'DataService.save',
    notify: true,
    logLevel: 'error'
  });
}

Create Custom Error

const error = ErrorManager.createError(
  'User {0} not found in {1}',
  ['john', 'database']
);
throw error;
// Error: "User john not found in database"

Handle Options

ErrorManager.handle(error, {
  // Context - where error occurred
  context: 'ComponentName.methodName',

  // Notify user via NotificationManager
  notify: true,

  // Log level: 'log', 'info', 'warn', 'error'
  logLevel: 'error',

  // Additional data
  data: {
    userId: 123,
    action: 'save'
  },

  // Event type to emit
  type: 'error:custom',

  // Force debug output
  debug: true
});

การตั้งค่า

ErrorManager.init({
  // Show stack traces in console
  debug: true,

  // Duration for notification display (ms)
  notificationDuration: 5000
});

API อ้างอิง

ErrorManager.init(options)

Initialize ErrorManager

Parameter Type Description
options.debug boolean Enable debug mode
options.notificationDuration number Notification duration (ms)

ErrorManager.handle(error, options)

Handle error

Parameter Type Description
error Error/string Error object หรือ message
options.context string Context ที่เกิด error
options.notify boolean แสดง notification
options.logLevel string 'log', 'info', 'warn', 'error'
options.data object ข้อมูลเพิ่มเติม
options.type string Event type ที่จะ emit

Returns: Error - Normalized error object

ErrorManager.createError(message, params)

สร้าง error พร้อม parameter substitution

Parameter Type Description
message string Error message with {0}, {1} placeholders
params array Parameters for substitution

Returns: Error

const error = ErrorManager.createError(
  'Cannot find {0} in {1}',
  ['item', 'collection']
);
// Error: "Cannot find item in collection"

ErrorManager.normalizeError(error)

Normalize error to Error object

Parameter Type Description
error any Error, string, หรืออื่นๆ

Returns: Error

เหตุการณ์

เมื่อระบุ type ใน options:

ErrorManager.handle(error, {
  type: 'error:api'
});

// Listen
EventManager.on('error:api', (data) => {
  console.log('API Error:', data.message);
  console.log('Context:', data.context);
});

ตัวอย่างการใช้งานจริง

API Error Handling

async function fetchData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    ErrorManager.handle(error, {
      context: 'fetchData',
      notify: true,
      type: 'error:fetch',
      data: { url }
    });
    return null;
  }
}

Form Validation Error

function validateForm(data) {
  const errors = [];

  if (!data.email) {
    errors.push('Email is required');
  }

  if (!data.password) {
    errors.push('Password is required');
  }

  if (errors.length > 0) {
    ErrorManager.handle(errors.join(', '), {
      context: 'FormValidation',
      notify: true,
      logLevel: 'warn'
    });
    return false;
  }

  return true;
}

Global Error Handler

// Catch unhandled errors
window.addEventListener('error', (event) => {
  ErrorManager.handle(event.error, {
    context: 'GlobalError',
    notify: true,
    type: 'error:global'
  });
});

// Catch unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
  ErrorManager.handle(event.reason, {
    context: 'UnhandledPromise',
    notify: true,
    type: 'error:unhandled'
  });
});

ข้อควรระวัง

⚠️ 1. ปิด Debug ใน Production

// ❌ Debug เปิดใน production
ErrorManager.init({ debug: true });

// ✅ ปิดใน production
ErrorManager.init({
  debug: process.env.NODE_ENV !== 'production'
});

⚠️ 2. อย่า Expose Sensitive Data

// ❌ Log sensitive data
ErrorManager.handle(error, {
  data: { password: user.password }
});

// ✅ Log safe data only
ErrorManager.handle(error, {
  data: { userId: user.id }
});

เอกสารที่เกี่ยวข้อง