Skip to content

Commit

Permalink
Make error type record constructors extend JavaScript Errors.
Browse files Browse the repository at this point in the history
  • Loading branch information
mtth committed Oct 26, 2015
1 parent ba44c91 commit d116b91
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
13 changes: 10 additions & 3 deletions lib/types.js
Expand Up @@ -1169,20 +1169,22 @@ function RecordType(schema, opts) {
return new Field(f, opts);
});

this._constructor = this._createConstructor();
this._constructor = this._createConstructor(schema.type === 'error');
this._read = this._createReader();
this._skip = this._createSkipper();
this._write = this._createWriter();
this.isValid = this._createChecker();
}
util.inherits(RecordType, Type);

RecordType.prototype._createConstructor = function () {
RecordType.prototype._createConstructor = function (isError) {
// jshint -W054
var outerArgs = [];
var innerArgs = [];
var innerBody = '';
var ds = []; // Defaults.
var innerBody = isError ? ' Error.call(this);\n' : '';
// Not calling `Error.captureStackTrace` because this wouldn't be compatible
// with browsers other than Chrome.
var i, l, field, name, getDefault;
for (i = 0, l = this._fields.length; i < l; i++) {
field = this._fields[i];
Expand Down Expand Up @@ -1217,6 +1219,11 @@ RecordType.prototype._createConstructor = function () {
// The names of these properties added to the prototype are prefixed with `$`
// because it is an invalid property name in Avro but not in JavaScript.
// (This way we are guaranteed not to be stepped over!)
if (isError) {
util.inherits(Record, Error);
// Not setting the name on the prototype to be consistent with how object
// fields are mapped to (only if defined in the schema as a field).
}

return Record;
};
Expand Down
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "avsc",
"version": "2.2.0",
"version": "2.2.1",
"description": "A serialization API to make you smile",
"homepage": "https://github.com/mtth/avsc",
"keywords": [
Expand Down
11 changes: 11 additions & 0 deletions test/test_types.js
Expand Up @@ -1688,6 +1688,17 @@ suite('types', function () {
}); });
});

test('error type', function () {
var t = fromSchema({
type: 'error',
name: 'Ouch',
fields: [{name: 'name', type: 'string'}]
});
var E = t.getRecordConstructor();
var err = new E('MyError');
assert(err instanceof Error);
});

});

suite('fromSchema', function () {
Expand Down

0 comments on commit d116b91

Please sign in to comment.