Lỗi thời gian chạy dẫn đến các đối tượng 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ả
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
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.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;
}
}
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;
}
}
3Tạ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;
}
}
5Tạ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;
}
}
6Tạ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;
}
}
7Tạ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;
}
}
8Tạ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;
}
}
9Tạ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;
}
}
2Tạ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-standardTạ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;
}
}
5Tạ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-standardHà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-standardMộ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 OptionalChứ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];
}
}
1Thô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];
}
}
3Tê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];
}
}
4Lỗ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-standardMộ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-standardMộ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-standardMộ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
}
1Trả 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 Error
0, 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 Error
0 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 Error
0 trong dấu vết ngăn xếp khi sử dụng các lớp ES2015. Some browsers include the Error
0 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 Error
0 trong dấu vết ngăn xếp khi sử dụng khai báo nguyên mẫu. All browsers include the Error
0 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
Đặ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ợ
6 có sẵn trongclass MyError extends Error { constructor[/* some arguments */] { // Needs to pass both `message` and `options` to install the "cause" property. super[message, options]; } }
Error
5
4class 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 }
5class 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 }
- Tài liệu V8 cho
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à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.class MyError extends Error { constructor[/* some arguments */] { // Needs to pass both `message` and `options` to install the "cause" property. super[message, options]; } }