繁体   English   中英

如何覆盖内置异常?

[英]How to override the built-in exception?

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

我已经尝试在第一个catch块中使用另一个try-catch,这可以完成工作。 但是我想在第一个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}"`
}

我期望My Exception: "this is my custom error message.."

使用console.error(er)

let x = 3
try {
    x.pop();
}
catch (e) {

        var er = thisErr("this is my custom error message..");
        // log(black)  My Exception: "this is my custom error message.."
        console.log(er);
        // error(red)  My Exception: "this is my custom error message.."
        console.error(er);
        // error(red) Uncaught My Exception: "this is my custom error message.."
        throw er;

}
function thisErr(message) {
    let moreInfo = message
    let name = "My Exception"
    return `${name}: "${moreInfo}"`
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM