From 39832c06338c3412bae22597acfc98002d4519bf Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Fri, 2 Nov 2012 10:39:49 -0700 Subject: [PATCH] Fix handling of Errors in Chrome --- lib/handlebars/utils.js | 10 ++++++---- spec/qunit_spec.js | 24 +++++++++++++++++++----- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/lib/handlebars/utils.js b/lib/handlebars/utils.js index b53c9ef45..3bc7e9b59 100644 --- a/lib/handlebars/utils.js +++ b/lib/handlebars/utils.js @@ -1,14 +1,16 @@ var Handlebars = require("./base"); // BEGIN(BROWSER) + +var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; + Handlebars.Exception = function(message) { var tmp = Error.prototype.constructor.apply(this, arguments); - for (var p in tmp) { - if (tmp.hasOwnProperty(p)) { this[p] = tmp[p]; } + // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. + for (var idx = 0; idx < errorProps.length; idx++) { + this[errorProps[idx]] = tmp[errorProps[idx]]; } - - this.message = tmp.message; }; Handlebars.Exception.prototype = new Error(); diff --git a/spec/qunit_spec.js b/spec/qunit_spec.js index 293c41317..5c9425396 100644 --- a/spec/qunit_spec.js +++ b/spec/qunit_spec.js @@ -61,13 +61,27 @@ function compileWithPartials(string, hashOrArray, partials) { } function shouldThrow(fn, exception, message) { - var caught = false; + var caught = false, + exType, exMessage; + + if (exception instanceof Array) { + exType = exception[0]; + exMessage = exception[1]; + } else if (typeof exception === 'string') { + exType = Error; + exMessage = exception; + } else { + exType = exception; + } + try { fn(); } catch (e) { - if (e instanceof exception) { - caught = true; + if (e instanceof exType) { + if (!exMessage || e.message === exMessage) { + caught = true; + } } } @@ -480,14 +494,14 @@ test("rendering undefined partial throws an exception", function() { shouldThrow(function() { var template = CompilerContext.compile("{{> whatever}}"); template(); - }, Handlebars.Exception, "Should throw exception"); + }, [Handlebars.Exception, 'The partial whatever could not be found'], "Should throw exception"); }); test("rendering template partial in vm mode throws an exception", function() { shouldThrow(function() { var template = CompilerContext.compile("{{> whatever}}"); template(); - }, Handlebars.Exception, "Should throw exception"); + }, [Handlebars.Exception, 'The partial whatever could not be found'], "Should throw exception"); }); test("rendering function partial in vm mode", function() {