为什么在抛出实例时我的自定义异常 class 类型会丢失上下文?

Why is my custom exception class type losing context when an instance is thrown?

我的对象上下文不在我期望的位置。

抛出的应该是class类型,但抓到的时候是对象。 为什么会这样? 可能是愚蠢的事情。几乎总是如此。

我不得不使用一个旧的未知 JS 运行时间。它无法升级,所以我无法使用更新的功能等

我把代码移植到Node中的运行所以它在导入和导出方面略有不同,但原型和功能是相同的。行为也相同:不需要。

这个ClassA提供了测试用例。

import ClassB from "./ClassB.js"
import ExceptionC from "./ClassB.js"

export default function ClassA() {};

ClassA.prototype = {
    objB: new ClassB(),

    funcA: function() {
        try {
            this.objB.thrower();
        }
        catch (thrownFromB) {
            console.log("Caught Exception. This exception instance should be an ExceptionC. It is type:" + typeof thrownFromB);
            if (thrownFromB instanceof ExceptionC) {
                console.log("ExceptionC message: " + thrownFromB.message + "  origError: " + thrownFromB.origError);
            }
        }
    }
};

此 ClassB 还提供抛出和自定义异常 class。

export default function ClassB() {};

ClassB.prototype = {
    AugmentedException: function(errorMsg, origError) {
        Error.call(this);
        this.message = errorMsg;
        this.origError = origError;
    },

    ExceptionC: function(errorMsg, origError) {
        AugmentedException.call(this, errorMsg, origError);
    },

    thrower: function() {
        console.log("throwing a new ExceptionC");
        throw new ExceptionC("foo", "bar");
    }
};

这是主要功能。

import ClassA from "./ClassA.js"

var foo = new ClassA();
foo.funcA();

这是输出。

>> OUTPUT:
>> throwing a new ExceptionC...
>> Caught Exception. This exception instance should be an ExceptionC. It is type: object

我怀疑的一些问题:

  1. ClassB.js中你使用了一些未定义的变量。因此,抛出 ReferenceError 而不是 ExceptionC。所以在这些行中:

    AugmentedException.call(this, errorMsg, origError);
    // ...
    throw new ExceptionC("foo", "bar");
    

    你可能是这个意思:

    ClassB.prototype.AugmentedException.call(this, errorMsg, origError);
    // ...
    throw new ClassB.prototype.ExceptionC("foo", "bar");
    
  2. ClassA.js 中,您将相同的导出默认值 class 导入到 2 个不同的变量中。因此,在 ExceptionC 中,您实际上拥有相同的 ClassB。所以在这一行中:

    import ExceptionC from "./ClassB.js"
    

    你可能是这个意思:

    const ExceptionC = ClassB.prototype.ExceptionC;
    

有了这些变化,我得到了预期:

throwing a new ExceptionC
Caught Exception. This exception instance should be an ExceptionC. It is type:object
ExceptionC message: foo  origError: bar