Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New error function to quickly extend new JS errors #1052

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 35 additions & 0 deletions index.html
Expand Up @@ -307,6 +307,7 @@
<li>- <a href="#unescape">unescape</a></li>
<li>- <a href="#result">result</a></li>
<li>- <a href="#template">template</a></li>
<li>- <a href="#error">error</a></li>
</ul>

<a class="toc_title" href="#chaining">
Expand Down Expand Up @@ -1651,6 +1652,40 @@ <h2 id="utility">Utility Functions</h2>
JST.project = <%= _.template(jstText).source %>;
&lt;/script&gt;</pre>

<p id="error">
<b class="header">error</b><code>_.error(errorMessage, [AbstractError])</code>
<br />
Helps create new JavaScript errors. If an abstract error is not provided, <b>error</b> will extend the generic JavaScript <tt>Error</tt>.
</p>

<pre>
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'</pre>

<p>To build a more specific error, provide an <b>AbstractError</b> to extend:</p>

<pre>
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;</pre>

<h2 id="chaining">Chaining</h2>

Expand Down
16 changes: 16 additions & 0 deletions test/utility.js
Expand Up @@ -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);
})

});
10 changes: 10 additions & 0 deletions underscore.js
Expand Up @@ -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();
Expand Down