From 97a362f7d088bbbf593ff004d3a5bff42df1e8f2 Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Tue, 16 Apr 2013 06:54:38 -0700 Subject: [PATCH] add debug(err) support. Closes #46 --- debug.js | 11 +++++++++++ example/worker.js | 6 +++++- lib/debug.js | 13 +++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/debug.js b/debug.js index e47ba5b..98cab11 100644 --- a/debug.js +++ b/debug.js @@ -17,6 +17,8 @@ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ + fmt = coerce(fmt); + var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; @@ -119,6 +121,15 @@ debug.enabled = function(name) { return false; }; +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack; + return val; +} + // persist if (window.localStorage) debug.enable(localStorage.debug); diff --git a/example/worker.js b/example/worker.js index 7f6d288..22225f6 100644 --- a/example/worker.js +++ b/example/worker.js @@ -19,4 +19,8 @@ function workb() { setTimeout(workb, Math.random() * 2000); } -workb(); \ No newline at end of file +workb(); + +setTimeout(function(){ + b(new Error('fail')); +}, 5000); diff --git a/lib/debug.js b/lib/debug.js index 0b07aa1..8e2b841 100644 --- a/lib/debug.js +++ b/lib/debug.js @@ -108,6 +108,8 @@ function debug(name) { var c = color(); function colored(fmt) { + fmt = coerce(fmt); + var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; @@ -121,6 +123,8 @@ function debug(name) { } function plain(fmt) { + fmt = coerce(fmt); + fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); @@ -132,3 +136,12 @@ function debug(name) { ? colored : plain; } + +/** + * Coerce `val`. + */ + +function coerce(val) { + if (val instanceof Error) return val.stack; + return val; +}