Permalink
Browse files

add callsite support for auto-generated messages

  • Loading branch information...
1 parent 046c701 commit 569f965749217f4485ae4622ba444d76119e589f @tj tj committed Oct 10, 2012
Showing with 69 additions and 2 deletions.
  1. +3 −1 component.json
  2. +6 −0 example.html
  3. +13 −0 example.js
  4. +47 −1 index.js
View
@@ -3,7 +3,9 @@
"description": "Assertion lib",
"version": "0.0.1",
"keywords": ["assert", "test"],
- "dependencies": {},
+ "dependencies": {
+ "component/stack": "*"
+ },
"scripts": [
"index.js"
]
View
@@ -0,0 +1,6 @@
+<html>
+ <body>
+ <script src="build/build.js"></script>
+ <script src="example.js"></script>
+ </body>
+</html>
View
@@ -0,0 +1,13 @@
+
+/**
+ * Module dependencies.
+ */
+
+var assert = require('assert');
+
+function test() {
+ var user = { name: 'Tobi' };
+ assert(user.name == 'tobi');
+}
+
+test();
View
@@ -1,4 +1,50 @@
+/**
+ * Module dependencies.
+ */
+
+var stack = require('stack');
+
+/**
+ * Load contents of `script`.
+ *
+ * @param {String} script
+ * @return {String}
+ * @api private
+ */
+
+function getScript(script) {
+ var xhr = new XMLHttpRequest;
+ xhr.open('GET', script, false);
+ xhr.send(null);
+ return xhr.responseText;
+}
+
+/**
+ * Assert `expr` with optional failure `msg`.
+ *
+ * @param {Mixed} expr
+ * @param {String} [msg]
+ * @api public
+ */
+
module.exports = function(expr, msg){
- if (!expr) throw new Error(msg || 'assertion failed');
+ if (expr) return;
+ if (!msg) {
+ if (Error.captureStackTrace) {
+ var callsite = stack()[1];
+ var fn = callsite.fun.toString();
+ var file = callsite.getFileName();
+ var line = callsite.getLineNumber() - 1;
+ var col = callsite.getColumnNumber() - 1;
+ var src = getScript(file);
+ line = src.split('\n')[line].slice(col);
+ expr = line.match(/assert\((.*?)\)/)[1].trim();
+ msg = expr;
+ } else {
+ msg = 'assertion failed';
+ }
+ }
+
+ throw new Error(msg);
};

0 comments on commit 569f965

Please sign in to comment.