Custom exception type

前端 未结 13 1703
生来不讨喜
生来不讨喜 2020-11-28 17:40

Can I define custom types for user-defined exceptions in JavaScript? If so, how would I do it?

13条回答
  •  失恋的感觉
    2020-11-28 18:07

    See this example in the MDN.

    If you need to define multiple Errors (test the code here!):

    function createErrorType(name, initFunction) {
        function E(message) {
            this.message = message;
            if (Error.captureStackTrace)
                Error.captureStackTrace(this, this.constructor);
            else
                this.stack = (new Error()).stack;
            initFunction && initFunction.apply(this, arguments);
        }
        E.prototype = Object.create(Error.prototype);
        E.prototype.name = name;
        E.prototype.constructor = E;
        return E;
    }
    var InvalidStateError = createErrorType(
        'InvalidStateError',
        function (invalidState, acceptedStates) {
            this.message = 'The state ' + invalidState + ' is invalid. Expected ' + acceptedStates + '.';
        });
    
    var error = new InvalidStateError('foo', 'bar or baz');
    function assert(condition) { if (!condition) throw new Error(); }
    assert(error.message);
    assert(error instanceof InvalidStateError);  
    assert(error instanceof Error); 
    assert(error.name == 'InvalidStateError');
    assert(error.stack);
    error.message;
    

    Code is mostly copied from: What's a good way to extend Error in JavaScript?

提交回复
热议问题