Javascript 如何覆盖内置异常?

Javascript 如何覆盖内置异常?,javascript,error-handling,try-catch,throw,Javascript,Error Handling,Try Catch,Throw,我正在整数变量上使用array.pop()函数,预期会出现错误。 目前,我收到“TypeError:x.pop不是函数”消息。 我想用我自己的消息“throw”来覆盖它 我试着在第一个catch块中使用另一个try-catch,这样就完成了任务。但是我想覆盖first try块本身中的第一个TypeError异常 let x = 3 try { x.pop(); // I want to override the exception generated due to this line

我正在整数变量上使用array.pop()函数,预期会出现错误。 目前,我收到“TypeError:x.pop不是函数”消息。 我想用我自己的消息“throw”来覆盖它

我试着在第一个catch块中使用另一个try-catch,这样就完成了任务。但是我想覆盖first try块本身中的第一个
TypeError
异常

let x = 3
try {
    x.pop();
// I want to override the exception generated due to this line 
// with my own error message using throw
}
catch (e) {
    try {
        throw thisErr("this is my custom error message..")
    }
    catch (er) {
        console.log(er);
    }
}

function thisErr(message) {
    let moreInfo = message
    let name = "My Exception"
    return `${name}: "${moreInfo}"`
}
我期待
我的异常:“这是我的自定义错误消息…”

使用
控制台。错误(er)

使用
控制台。错误(er)


快速方法: 您可以使用错误构造函数创建错误对象,并将其用作定义自定义异常的基础。当没有多个实例需要抛出自定义异常时,通常可以使用此方法

let x = 3;
try {
    x.pop();
} catch (e) {
    throw new Error({ 
        name: "My Exception",
        message: "this is my custom error message..", 
        toString: function() { return `${this.name} : ${this.message}` } 
    });
}
更好的方法: 创建一个CustomError类,并为此自定义类定义自己的构造函数。这种方法更好、更健壮,可以在应用程序在许多地方需要自定义异常时使用

class CustomError extends Error {
    constructor(name, message, ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent 
    constructor
        super(...params);

        this.name = name;
        this.message = message;

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

let x = 3;
try {
    x.pop();
} catch(e){
    throw new CustomError('My Exception', 'this is my custom error message..', e);
}

快速方法: 您可以使用错误构造函数创建错误对象,并将其用作定义自定义异常的基础。当没有多个实例需要抛出自定义异常时,通常可以使用此方法

let x = 3;
try {
    x.pop();
} catch (e) {
    throw new Error({ 
        name: "My Exception",
        message: "this is my custom error message..", 
        toString: function() { return `${this.name} : ${this.message}` } 
    });
}
更好的方法: 创建一个CustomError类,并为此自定义类定义自己的构造函数。这种方法更好、更健壮,可以在应用程序在许多地方需要自定义异常时使用

class CustomError extends Error {
    constructor(name, message, ...params) {
    // Pass remaining arguments (including vendor specific ones) to parent 
    constructor
        super(...params);

        this.name = name;
        this.message = message;

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

let x = 3;
try {
    x.pop();
} catch(e){
    throw new CustomError('My Exception', 'this is my custom error message..', e);
}