Skip to content

Commit

Permalink
Merge pull request #53 from trentmwillis/metrics
Browse files Browse the repository at this point in the history
Properly handle errors when thrown inside measured function
  • Loading branch information
stefanpenner authored Apr 4, 2017
2 parents 75285ea + 4c048cf commit 8b9e595
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
18 changes: 14 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,26 @@ function defineFunction(obj, name, fn) {

metrics.start();

var result = fn.apply(this, arguments);
var result;
var didError = true;

try {
result = fn.apply(this, arguments);
didError = false;
} finally {
if (didError) {
metrics.stop();
}
}

if (typeof result.finally === 'function') {
return result.finally(function() {
metrics.stop();
});
} else {
metrics.stop();
return result;
}

metrics.stop();
return result;
};
}

Expand Down
6 changes: 6 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ var expect = chai.expect;
var RSVP = require('rsvp');
var Mode = require('stat-mode');
var crypto = require('crypto');
var heimdall = require('heimdalljs');

describe('cache', function() {
var cache;
Expand Down Expand Up @@ -114,6 +115,11 @@ describe('cache', function() {
})
]);
});

it('properly stops metrics when an error occurs', function() {
expect(function() { cache.pathFor(); }).to.throw();
expect(heimdall.statsFor('async-disk-cache').pathFor.startTime).to.be.undefined;
});
});

var zlib = require('zlib');
Expand Down

0 comments on commit 8b9e595

Please sign in to comment.