From 9db110eff89a83b1be3516c97443b21f22c5e690 Mon Sep 17 00:00:00 2001 From: Eric Vicenti Date: Thu, 4 Apr 2013 21:55:16 -0700 Subject: [PATCH] Add error function to quickly extend new js errors --- index.html | 35 +++++++++++++++++++++++++++++++++++ test/utility.js | 16 ++++++++++++++++ underscore.js | 10 ++++++++++ 3 files changed, 61 insertions(+) diff --git a/index.html b/index.html index f18c8f276..3aafc9056 100644 --- a/index.html +++ b/index.html @@ -307,6 +307,7 @@
  • - unescape
  • - result
  • - template
  • +
  • - error
  • @@ -1651,6 +1652,40 @@

    Utility Functions

    JST.project = <%= _.template(jstText).source %>; </script> +

    + error_.error(errorMessage, [AbstractError]) +
    + Helps create new JavaScript errors. If an abstract error is not provided, error will extend the generic JavaScript Error. +

    + +
    +var FOO_ERROR = _.error('There was an error with FOO');
    +
    +var e = new FOO_ERROR();
    +
    +e instanceof Error
    +=> true
    +
    +e instanceof FOO_ERROR
    +=> true
    +
    +e.message
    +=> 'There was an error with FOO'
    + +

    To build a more specific error, provide an AbstractError to extend:

    + +
    +var FOO_AUTH_ERROR = _.error('FOO could not authenticate', FOO_ERROR);
    +
    +var e = new FOO_AUTH_ERROR();
    +
    +e instanceof FOO_ERROR
    +=> true
    +
    +e.message
    +=> 'FOO could not authenticate'
    +
    +throw e;

    Chaining

    diff --git a/test/utility.js b/test/utility.js index 4797872a1..e14c9afd6 100644 --- a/test/utility.js +++ b/test/utility.js @@ -267,4 +267,20 @@ $(document).ready(function() { strictEqual(template(), '<<\nx\n>>'); }); + test('error', 6, function(){ + var errorMsg = 'oh, no!'; + var MyError = _.error(errorMsg); + var error = new MyError(); + ok(error instanceof Error); + ok(error instanceof MyError) + ok(error.message === errorMsg); + + var specificErrorMsg = 'this error is even more useful'; + var SpecificError = _.error(specificErrorMsg, MyError); + error = new SpecificError(); + ok(error instanceof MyError); + ok(error instanceof SpecificError); + ok(error.message === specificErrorMsg); + }) + }); diff --git a/underscore.js b/underscore.js index 27f352e02..0ae4d312d 100644 --- a/underscore.js +++ b/underscore.js @@ -1193,6 +1193,16 @@ return template; }; + // Automate the creation of errors + _.error = function(msg, AbstractError){ + AbstractError || (AbstractError = Error); + var E = function(msg){ + if(msg) this.message = msg; + } + E.prototype = new AbstractError(msg); + return E; + } + // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain();