Custom exception type

前端 未结 13 1717
生来不讨喜
生来不讨喜 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:17

    I often use an approach with prototypal inheritance. Overriding toString() gives you the advantage that tools like Firebug will log the actual information instead of [object Object] to the console for uncaught exceptions.

    Use instanceof to determine the type of exception.

    main.js

    // just an exemplary namespace
    var ns = ns || {};
    
    // include JavaScript of the following
    // source files here (e.g. by concatenation)
    
    var someId = 42;
    throw new ns.DuplicateIdException('Another item with ID ' +
        someId + ' has been created');
    // Firebug console:
    // uncaught exception: [Duplicate ID] Another item with ID 42 has been created
    

    Exception.js

    ns.Exception = function() {
    }
    
    /**
     * Form a string of relevant information.
     *
     * When providing this method, tools like Firebug show the returned 
     * string instead of [object Object] for uncaught exceptions.
     *
     * @return {String} information about the exception
     */
    ns.Exception.prototype.toString = function() {
        var name = this.name || 'unknown';
        var message = this.message || 'no description';
        return '[' + name + '] ' + message;
    };
    

    DuplicateIdException.js

    ns.DuplicateIdException = function(message) {
        this.name = 'Duplicate ID';
        this.message = message;
    };
    
    ns.DuplicateIdException.prototype = new ns.Exception();
    

提交回复
热议问题