Custom exception type

前端 未结 13 1699
生来不讨喜
生来不讨喜 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?

    0 讨论(0)
  • 2020-11-28 18:10
    function MyError(message) {
     this.message = message;
    }
    
    MyError.prototype = new Error;
    

    This allows for usage like..

    try {
      something();
     } catch(e) {
      if(e instanceof MyError)
       doSomethingElse();
      else if(e instanceof Error)
       andNowForSomethingCompletelyDifferent();
    }
    
    0 讨论(0)
  • 2020-11-28 18:15

    ES6

    With the new class and extend keywords it’s now much easier:

    class CustomError extends Error {
      constructor(message) {
        super(message);
        //something
      }
    }
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-28 18:20

    Yes. You can throw anything you want: integers, strings, objects, whatever. If you want to throw an object, then simply create a new object, just as you would create one under other circumstances, and then throw it. Mozilla's Javascript reference has several examples.

    0 讨论(0)
  • From WebReference:

    throw { 
      name:        "System Error", 
      level:       "Show Stopper", 
      message:     "Error detected. Please contact the system administrator.", 
      htmlMessage: "Error detected. Please contact the <a href=\"mailto:sysadmin@acme-widgets.com\">system administrator</a>.",
      toString:    function(){return this.name + ": " + this.message;} 
    }; 
    
    0 讨论(0)
提交回复
热议问题