Hướng dẫn what happens when a javascript error occurs? - điều gì xảy ra khi lỗi javascript xảy ra?

Error Các đố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

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 hoặc được sao chép giữa các công nhân bằng cách sử dụ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;
  }
}
1.

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;
  }
}
3

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;
  }
}
4.

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 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;
  }
}
6

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;
  }
}
7

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;
  }
}
8

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;
  }
}
9

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

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 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;
  }
}
1 đượ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;
  }
}
2

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;
  }
}
3.

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 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;
  }
}
5

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;
  }
}
7 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;
  }
}
8 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;
  }
}
9 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.

class MyError extends Error {
  constructor(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
0 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(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
1

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(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
3

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(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
4

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(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
6 của đối số thứ hai của nhà xây dựng.

class MyError extends Error {
  constructor(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
7 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(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
8 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(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
9 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 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 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
}
1

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
}
2.

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 mục đích 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
}
4. 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
}
5:

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
}
6 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
}
7: 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ố Constructor

function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

try {
  throw new CustomError('baz', 'bazMessage');
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
}
0 (thuộc tính
class MyError extends Error {
  constructor(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
6), vì đ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ự (

function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

try {
  throw new CustomError('baz', 'bazMessage');
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
}
2 và
function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

try {
  throw new CustomError('baz', 'bazMessage');
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
}
3):

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(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}
6, với điều kiện hàm tạo của các lớp con vượt qua tham số
function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

try {
  throw new CustomError('baz', 'bazMessage');
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
}
5 khi gọi
function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

try {
  throw new CustomError('baz', 'bazMessage');
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
}
6:

class MyError extends Error {
  constructor(/* some arguments */) {
    // Needs to pass both `message` and `options` to install the "cause" property.
    super(message, options);
  }
}

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ể

function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

try {
  throw new CustomError('baz', 'bazMessage');
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
}
8 và sử dụng
function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

try {
  throw new CustomError('baz', 'bazMessage');
} catch (e) {
  console.error(e.name); // CustomError
  console.error(e.foo); // baz
  console.error(e.message); // bazMessage
}
9 để 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ớp Es6 CustomError

CẢNH BÁO: Các phiên bản của Babel trước 7 có thể xử lý các phương thức lớp Error0, nhưng chỉ khi chúng được khai báo với Object.defineProperty (). Mặt khác, các phiên bản cũ của Babel và các bộ chuyển đổi khác sẽ không xử lý chính xác mã sau mà không có cấu hình bổ sung. Versions of Babel prior to 7 can handle Error0 class methods, but only when they are declared with Object.defineProperty(). Otherwise, old versions of Babel and other transpilers will not correctly handle the following code without additional configuration.

Lưu ý: Một số trình duyệt bao gồm hàm tạo Error0 trong dấu vết ngăn xếp khi sử dụng các lớp ES2015. Some browsers include the Error0 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
}

Đối tượng ES5 CustomError

CẢNH BÁO: Tất cả các trình duyệt bao gồm hàm tạo Error0 trong dấu vết ngăn xếp khi sử dụng khai báo nguyên mẫu. All browsers include the Error0 constructor in the stack trace when using a prototypal declaration.

function CustomError(foo, message, fileName, lineNumber) {
  var instance = new Error(message, fileName, lineNumber);
  instance.foo = foo;
  Object.setPrototypeOf(instance, CustomError.prototype);
  if (Error.captureStackTrace) {
    Error.captureStackTrace(instance, CustomError);
  }
  return instance;
}

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

Object.setPrototypeOf(CustomError, Error);

CustomError.prototype.name = 'CustomError';

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

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(/* some arguments */) {
        // Needs to pass both `message` and `options` to install the "cause" property.
        super(message, options);
      }
    }
    
    6 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
    }
    
    4
  • 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
  • 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;
      }
    }
    
    7,
    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 và
    class MyError extends Error {
      constructor(/* some arguments */) {
        // Needs to pass both `message` and `options` to install the "cause" property.
        super(message, options);
      }
    }
    
    0.

Điều gì xảy ra khi JavaScript ném lỗi?

Khi xảy ra lỗi, JavaScript thường sẽ dừng và tạo thông báo lỗi. Thuật ngữ kỹ thuật cho điều này là: JavaScript sẽ ném một ngoại lệ (ném lỗi). JavaScript thực sự sẽ tạo một đối tượng lỗi với hai thuộc tính: tên và tin nhắn.JavaScript will normally stop and generate an error message. The technical term for this is: JavaScript will throw an exception (throw an error). JavaScript will actually create an Error object with two properties: name and message.

Sự kiện nào xảy ra khi có lỗi JavaScript?

Phương thức OnError () Trình xử lý sự kiện OnError là tính năng đầu tiên tạo điều kiện cho việc xử lý lỗi trong JavaScript. Sự kiện lỗi được kích hoạt trên đối tượng cửa sổ bất cứ khi nào xảy ra ngoại lệ trên trang.error event is fired on the window object whenever an exception occurs on the page.

Tại sao các lỗi JavaScript xảy ra?

Các lỗi này xảy ra khi công cụ JavaScript đang phân tích tập lệnh và gặp mã không hợp lệ về mặt cú pháp.Nếu tệp JavaScript chứa lỗi cú pháp, không có mã nào trong tệp sẽ thực thi.Mã này không chỉ tạo ra một lỗi, mà cả bảng điều khiển.Đăng nhập trước cú pháp không hợp lệ thậm chí sẽ không chạy.when the JavaScript engine is parsing a script and encounters syntactically invalid code. If a JavaScript file contains a syntax error, none of the code in the file will execute. Not only will this code produce an error, but the console. log before the invalid syntax won't even run.

Làm thế nào để bạn sửa lỗi JavaScript?

Khắc phục lỗi JavaScript..
Mở trang web demo lỗi JavaScript được báo cáo trong công cụ bảng điều khiển trong một cửa sổ hoặc tab mới ..
Nhấp chuột phải vào bất cứ nơi nào trong trang web và sau đó chọn Kiểm tra.Hoặc, nhấn F12.....
Nhấp vào nút Bảng điều khiển mở để xem lỗi ở phía trên bên phải.....
Nhấp vào lỗi ..