Hướng dẫn what is type error in javascript? - lỗi kiểu trong javascript là gì?

Error Đối tượng được ném khi xảy ra lỗi thời gian chạy. Đối tượng Error cũng có thể được sử dụng làm đối tượng cơ sở cho các ngoại lệ do người dùng xác định. Xem bên dưới để biết các loại lỗi tích hợp tiêu chuẩn.

Sự mô tả

Lỗi thời gian chạy dẫn đến các đối tượng Error mới được tạo và ném.

Error là một đối tượng có thể nối tiếp, vì vậy nó có thể được nhân bản với structuredClone() hoặc được sao chép giữa các công nhân bằng

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
0.

Loại lỗi

Bên cạnh hàm tạo Error chung, còn có các hàm tạo lỗi cốt lõi khác trong JavaScript. Đối với các ngoại lệ phía máy khách, hãy xem các báo cáo xử lý ngoại lệ.

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
2

Tạo một thể hiện biểu thị một lỗi xảy ra liên quan đến chức năng toàn cầu

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
3.

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
4

Tạo một thể hiện biểu thị một lỗi xảy ra khi một biến hoặc tham số số nằm ngoài phạm vi hợp lệ của nó.

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
5

Tạo một thể hiện biểu thị một lỗi xảy ra khi không tham chiếu tham chiếu không hợp lệ.

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
6

Tạo một thể hiện đại diện cho một lỗi cú pháp.

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
7

Tạo một thể hiện biểu thị một lỗi xảy ra khi một biến hoặc tham số không thuộc loại hợp lệ.

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
8

Tạo một thể hiện biểu thị một lỗi xảy ra khi

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}
9 hoặc
function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
0 được truyền các tham số không hợp lệ.

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
1

Tạo một thể hiện đại diện cho một số lỗi được bọc trong một lỗi duy nhất khi cần có nhiều lỗi được báo cáo bởi một thao tác, ví dụ như

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
2.

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
3 không chuẩnNon-standard

Tạo một thể hiện biểu thị một lỗi xảy ra khi lỗi bên trong trong công cụ JavaScript bị ném. Ví dụ. "Quá nhiều đệ quy".

Người xây dựng

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
4

Tạo một đối tượng Error mới.

Phương pháp tĩnh

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
6 không chuẩnNon-standard

Hàm V8 không chuẩn tạo thuộc tính

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
7 trên một thể hiện lỗi.

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
8 không chuẩnNon-standard

Một thuộc tính số V8 không chuẩn, giới hạn số lượng khung ngăn xếp trong một stacktrace lỗi.

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
9 không chuẩnNon-standard Optional

Chức năng V8 không chuẩn, nếu được cung cấp bởi UserCode, được gọi bởi động cơ JavaScript V8 cho các ngoại lệ ném, cho phép người dùng cung cấp định dạng tùy chỉnh cho các ngăn xếp.

Thuộc tính thể hiện

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
0

Thông báo lỗi. Đối với các đối tượng Error do người dùng tạo, đây là chuỗi được cung cấp dưới dạng đối số đầu tiên của trình xây dựng.

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
2

Tên lỗi. Điều này được xác định bởi hàm tạo hàm.

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
3

Lỗi nguyên nhân chỉ ra lý do tại sao lỗi hiện tại được ném - thường là một lỗi bị bắt khác. Đối với các đối tượng Error do người dùng tạo, đây là giá trị được cung cấp dưới dạng thuộc tính

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
5 của đối số thứ hai của nhà xây dựng.

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
6 không chuẩnNon-standard

Một thuộc tính Mozilla không chuẩn cho đường dẫn đến tệp đã nêu ra lỗi này.

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
7 không chuẩnNon-standard

Một thuộc tính Mozilla không chuẩn cho số dòng trong tệp đã nêu lỗi này.

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
8 không chuẩnNon-standard

Một thuộc tính Mozilla không chuẩn cho số cột trong dòng đã nêu ra lỗi này.

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
9 không chuẩnNon-standard

Một tài sản không chuẩn cho một dấu vết ngăn xếp.

Phương pháp thể hiện

class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
0

Trả về một chuỗi đại diện cho đối tượng được chỉ định. Ghi đè phương thức

class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
1.

Ví dụ

Ném một lỗi chung

Thông thường bạn tạo một đối tượng Error với ý định nâng cao nó bằng cách sử dụng từ khóa

class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
3. Bạn có thể xử lý lỗi bằng cách sử dụng cấu trúc
class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
4:

try {
  throw new Error("Whoops!");
} catch (e) {
  console.error(`${e.name}: ${e.message}`);
}

Xử lý một loại lỗi cụ thể

Bạn có thể chọn chỉ xử lý các loại lỗi cụ thể bằng cách kiểm tra loại lỗi với thuộc tính

class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
5 của lỗi hoặc, nếu bạn đang viết cho các công cụ JavaScript hiện đại, từ khóa
class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
6: từ khóa:

try {
  foo.bar();
} catch (e) {
  if (e instanceof EvalError) {
    console.error(`${e.name}: ${e.message}`);
  } else if (e instanceof RangeError) {
    console.error(`${e.name}: ${e.message}`);
  }
  // etc.
  else {
    // If none of our cases matched leave the Error unhandled
    throw e;
  }
}

Phân biệt giữa các lỗi tương tự

Đôi khi, một khối mã có thể thất bại vì những lý do yêu cầu xử lý khác nhau, nhưng ném các lỗi rất giống nhau (nghĩa là với cùng loại và thông báo).

Nếu bạn không có quyền kiểm soát các lỗi ban đầu được ném, một tùy chọn là bắt chúng và ném các đối tượng Error mới có thông điệp cụ thể hơn. Lỗi ban đầu phải được chuyển cho Error mới trong tham số

class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
9 của nhà xây dựng dưới dạng thuộc tính
class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
5 của nó. Điều này đảm bảo rằng lỗi gốc và dấu vết ngăn xếp có sẵn cho các khối thử/bắt cấp cao hơn.

Ví dụ dưới đây cho thấy điều này cho hai phương pháp sẽ thất bại với các lỗi tương tự (Error1 và Error2):

function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}

Lưu ý: Nếu bạn đang tạo thư viện, bạn nên sử dụng lỗi gây ra lỗi để phân biệt giữa các lỗi khác nhau - thay vì yêu cầu người tiêu dùng của bạn phân tích thông báo lỗi. Xem trang Nguyên nhân lỗi cho một ví dụ. If you are making a library, you should prefer to use error cause to discriminate between different errors emitted — rather than asking your consumers to parse the error message. See the error cause page for an example.

Các loại lỗi tùy chỉnh cũng có thể sử dụng thuộc tính

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
5, với điều kiện hàm tạo của các lớp con vượt qua tham số
class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}
9 khi gọi Error5. Trình xây dựng lớp cơ sở
function doWork() {
  try {
    doFailSomeWay();
  } catch (err) {
    throw new Error("Failed in some way", { cause: err });
  }
  try {
    doFailAnotherWay();
  } catch (err) {
    throw new Error("Failed in another way", { cause: err });
  }
}

try {
  doWork();
} catch (err) {
  switch (err.message) {
    case "Failed in some way":
      handleFailSomeWay(err.cause);
      break;
    case "Failed in another way":
      handleFailAnotherWay(err.cause);
      break;
  }
}
4 sẽ đọc Error7 và xác định thuộc tính
class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause
5 trên thể hiện lỗi mới.

class MyError extends Error {
  constructor(message, options) {
    // Need to pass `options` as the second parameter to install the "cause" property.
    super(message, options);
  }
}

console.log(new MyError("test", { cause: new Error("cause") }).cause);
// Error: cause

Các loại lỗi tùy chỉnh

Bạn có thể muốn xác định các loại lỗi của riêng mình xuất phát từ Error để có thể Error0 và sử dụng Error1 để kiểm tra loại lỗi trong trình xử lý ngoại lệ. Điều này dẫn đến mã xử lý lỗi sạch hơn và nhất quán hơn.

Xem "Cách tốt để gia hạn lỗi trong JavaScript là gì?" trên stackoverflow cho một cuộc thảo luận chuyên sâu.

Lưu ý: Một số trình duyệt bao gồm hàm tạo Error2 trong dấu vết ngăn xếp khi sử dụng các lớp ES2015. Some browsers include the Error2 constructor in the stack trace when using ES2015 classes.

class CustomError extends Error {
  constructor(foo = "bar", ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent constructor
    super(...params);

    // Maintains proper stack trace for where our error was thrown (only available on V8)
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CustomError);
    }

    this.name = "CustomError";
    // Custom debugging information
    this.foo = foo;
    this.date = new Date();
  }
}

try {
  throw new CustomError("baz", "bazMessage");
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
  console.error(e.stack); // stacktrace
}

Thông số kỹ thuật

Sự chỉ rõ
Đặc tả ngôn ngữ Ecmascript # Sec-Error-Epjects
# sec-error-objects

Tính tương thích của trình duyệt web

Bảng BCD chỉ tải trong trình duyệt

Xem thêm

  • Một polyfill của Error với hành vi hiện đại như hỗ trợ
    class MyError extends Error {
      constructor(message, options) {
        // Need to pass `options` as the second parameter to install the "cause" property.
        super(message, options);
      }
    }
    
    console.log(new MyError("test", { cause: new Error("cause") }).cause);
    // Error: cause
    
    5 có sẵn trong Error5
  • class CustomError extends Error {
      constructor(foo = "bar", ...params) {
        // Pass remaining arguments (including vendor specific ones) to parent constructor
        super(...params);
    
        // Maintains proper stack trace for where our error was thrown (only available on V8)
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, CustomError);
        }
    
        this.name = "CustomError";
        // Custom debugging information
        this.foo = foo;
        this.date = new Date();
      }
    }
    
    try {
      throw new CustomError("baz", "bazMessage");
    } catch (e) {
      console.error(e.name); // CustomError
      console.error(e.foo); // baz
      console.error(e.message); // bazMessage
      console.error(e.stack); // stacktrace
    }
    
    3
  • class CustomError extends Error {
      constructor(foo = "bar", ...params) {
        // Pass remaining arguments (including vendor specific ones) to parent constructor
        super(...params);
    
        // Maintains proper stack trace for where our error was thrown (only available on V8)
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, CustomError);
        }
    
        this.name = "CustomError";
        // Custom debugging information
        this.foo = foo;
        this.date = new Date();
      }
    }
    
    try {
      throw new CustomError("baz", "bazMessage");
    } catch (e) {
      console.error(e.name); // CustomError
      console.error(e.foo); // baz
      console.error(e.message); // bazMessage
      console.error(e.stack); // stacktrace
    }
    
    4
  • Tài liệu V8 cho
    function doWork() {
      try {
        doFailSomeWay();
      } catch (err) {
        throw new Error("Failed in some way", { cause: err });
      }
      try {
        doFailAnotherWay();
      } catch (err) {
        throw new Error("Failed in another way", { cause: err });
      }
    }
    
    try {
      doWork();
    } catch (err) {
      switch (err.message) {
        case "Failed in some way":
          handleFailSomeWay(err.cause);
          break;
        case "Failed in another way":
          handleFailAnotherWay(err.cause);
          break;
      }
    }
    
    6,
    function doWork() {
      try {
        doFailSomeWay();
      } catch (err) {
        throw new Error("Failed in some way", { cause: err });
      }
      try {
        doFailAnotherWay();
      } catch (err) {
        throw new Error("Failed in another way", { cause: err });
      }
    }
    
    try {
      doWork();
    } catch (err) {
      switch (err.message) {
        case "Failed in some way":
          handleFailSomeWay(err.cause);
          break;
        case "Failed in another way":
          handleFailAnotherWay(err.cause);
          break;
      }
    }
    
    8 và
    function doWork() {
      try {
        doFailSomeWay();
      } catch (err) {
        throw new Error("Failed in some way", { cause: err });
      }
      try {
        doFailAnotherWay();
      } catch (err) {
        throw new Error("Failed in another way", { cause: err });
      }
    }
    
    try {
      doWork();
    } catch (err) {
      switch (err.message) {
        case "Failed in some way":
          handleFailSomeWay(err.cause);
          break;
        case "Failed in another way":
          handleFailAnotherWay(err.cause);
          break;
      }
    }
    
    9.

Chức năng loại trong JavaScript là gì?

TypeOf là từ khóa JavaScript sẽ trả về loại biến khi bạn gọi nó. Bạn có thể sử dụng điều này để xác nhận các tham số chức năng hoặc kiểm tra nếu các biến được xác định. Có những công dụng khác là tốt. Toán tử typeof rất hữu ích vì nó là một cách dễ dàng để kiểm tra loại biến trong mã của bạn.a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.

Có bao nhiêu loại lỗi trong chương trình JavaScript?

Có 7 loại lỗi JavaScript: lỗi cú pháp, lỗi tham chiếu, lỗi loại, lỗi đánh giá, rangeRror, lỗi URI và lỗi nội bộ.7 types of JavaScript errors: Syntax error, Reference Error, Type Error, Evaluation Error, RangeError, URI Error and Internal Error.

Lỗi đối tượng trong JavaScript là gì?

Các đối tượng lỗi được ném khi xảy ra lỗi thời gian chạy.Đối tượng lỗi cũng có thể được sử dụng làm đối tượng cơ sở cho các ngoại lệ do người dùng xác định.Xem bên dưới để biết các loại lỗi tích hợp tiêu chuẩn.thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types.

Làm cách nào để khắc phục kiểu mẫu không phải là một chức năng?

Kiểu hàng: "X" không phải là một hàm có thể được sửa bằng cách sử dụng các đề xuất sau: chú ý đến chi tiết trong mã và giảm thiểu lỗi chính tả.Nhập các thư viện tập lệnh chính xác và có liên quan được sử dụng trong mã.Đảm bảo thuộc tính được gọi của một đối tượng thực sự là một hàm.Paying attention to detail in code and minimizing typos. Importing the correct and relevant script libraries used in code. Making sure the called property of an object is actually a function.