TritonDataCenter / node-verror

Rich JavaScript errors
MIT License
1.18k stars 61 forks source link

Allow the toString() name to come from a local 'name' property #7

Closed trentm closed 11 years ago

trentm commented 11 years ago

They just don't stop coming. :|

Mark mentioned that all the recent changes broke this usage: https://github.com/mcavage/node-fast/blob/master/lib/client.js#L216-217

I.e. No subclass, just tweaking <WError instance>.name.

If we want to support that and still support the "name comes from the constructor function name" then we need this patch.

Some more details if you care

Note that supporting the name from "this.constructor.name" is not a core node thing:

$ cat bar.js 
var util = require('util');
function MySubError () {
   // Warning: the following doesn't result in `this.message` being set
   // as I would have expected.
   Error.apply(this, Array.prototype.slice.call(arguments));
   // ... so have to:
   this.message = arguments[0];
}
util.inherits(MySubError, Error);

var s = new MySubError('sub boom');
console.log("s:", s.toString())
[12:56:59 trentm@banana:~/src/node-verror (master)]
$ node bar.js 
s: Error: sub boom

This means that the Error.prototype.toString() implementation is really easy:

return this.name + ': ' + this.message

Where as to handle the three cases we want we need:

var str = (this.hasOwnProperty('name') && this.name ||
    this.constructor.name || this.constructor.prototype.name);
if (this.message)
    str += ': ' + this.message;

return (str);

We can't just use: this.name || ... because this.name will look at this.constructor.prototype.name when walking the prototype chain and will mean this.constructor.name is never looked at.

I'm fine with this... just saying.