Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้ Custom Exceptions ใน JavaScript

ใช้คำสั่ง throw เพื่อโยน Custom Exceptions แล้วจับด้วย try...catch

ตัวอย่าง

<html>
  <head>
    <script>
      function myFunc() {
        var a = 100, b = 0;
        try {
          if (b == 0) {
            throw "Divide by zero error.";
          } else {
            var c = a / b;
          }
        } catch (e) {
          alert("Error: " + e);
        }
      }
    </script>
  </head>
  <body>
    <p>คลิกเพื่อดูผลลัพธ์:</p>
    <form>
      <input type="button" value="Click Me" onclick="myFunc();" />
    </form>
  </body>
</html>

แนวทางปฏิบัติที่ดีกว่า (Modern)

1. Throw Error Objects (มี Stack Trace)

throw new Error("Divide by zero");

2. Custom Error Classes (ES6)

class AppError extends Error {
  constructor(message, code, details) {
    super(message);
    this.name = "AppError";
    this.code = code;
    this.details = details;
  }
}

class ValidationError extends AppError {
  constructor(message, field) {
    super(message, "VALIDATION_ERROR");
    this.name = "ValidationError";
    this.field = field;
  }
}

3. ใช้งานพร้อม Error Handling แบบสมบูรณ์

function divide(a, b) {
  if (b === 0) throw new RangeError("Divisor cannot be zero");
  return a / b;
}

function processForm(data) {
  if (!data.email) throw new ValidationError("Email required", "email");
  if (!data.age || data.age < 18) throw new ValidationError("Must be 18+", "age");
  return saveUser(data);
}

try {
  const result = processForm({ email: "test@example.com", age: 25 });
} catch (e) {
  if (e instanceof ValidationError) {
    showFieldError(e.field, e.message);
  } else if (e instanceof RangeError) {
    showToast(e.message);
  } else {
    logError(e); // Unexpected error
    showGenericError();
  }
}

Error Handling Patterns

  • Fail Fast: Validate เร็ว Throw ทันที
  • Error Boundaries (React): จับ Error ใน Component Tree
  • Global Handler: window.addEventListener('error') สำหรับ Logging
  • Result Pattern: คืน {ok: true, data} | {ok: false, error} แทน Throw (Functional Style)