Emailing a JavaScript Error

I wanted to get an email whenever my SailsJS (based on ExpressJS) app crashed. My logging stack consists of winston with a custom transport which emails me via AmazonSES. Instead of getting a nice stack trace, all I got was emails with


which I couldn’t quite understand. Was I not passing the error object in? Was there somewhere in the SailsJS / Winston pipeline that was destroying my error object? A line of

 if (sails.config.environment === 'production') { data = undefined; }

seemed likely but wasn’t the culprit after all.

JavaScript’s Error object while having a `toString()` that will give `foo` from `new Error(‘foo’)`, calling `JSON.stringify(new Error(‘foo’))` will produce `{}` (empty object).

Extending the error proto to have a `toJSON` method, which gets called by `JSON.stringify()` can be done with:

Error.stackTraceLimit = Infinity;                   // Turtles all the way down, since we're already messing with Error
Object.defineProperty(Error.prototype, 'toJSON', {  // Give Error proto a toJSON method
  value: function () {
    var alt = {};
    Object.getOwnPropertyNames(this).forEach(function (key) {
      alt[key] = this[key];
    }, this);

    return alt;

  configurable: true,
  writable: true,

And now an error object can be passed into Winston to get transported to my inbox with full stack trace.

Codemonkey of Node.js, Django, PHP and all things HTML5 Solving tech challenges, one bit at a time.

Posted in email, javascript, nodejs, servers, wherewolf Tagged with: , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *