Skip to content

Commit

Permalink
Merge pull request #140 from canjs/improve-type-error-message
Browse files Browse the repository at this point in the history
Improve type error message
  • Loading branch information
cherifGsoul authored Oct 11, 2019
2 parents 83be9f4 + ea5b2c2 commit 5c56ee7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/define.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ var newSymbol = Symbol.for("can.new"),
inSetupSymbol = Symbol.for("can.initializing"),
isMemberSymbol = Symbol.for("can.isMember"),
hasBeenDefinedSymbol = Symbol.for("can.hasBeenDefined"),
canMetaSymbol = Symbol.for("can.meta");
canMetaSymbol = Symbol.for("can.meta"),
baseTypeSymbol = Symbol.for("can.baseType");

var eventsProto, define,
make, makeDefinition, getDefinitionsAndMethods, getDefinitionOrMethod;
Expand Down Expand Up @@ -688,6 +689,18 @@ make = {
return setter;
} else {
return function setter(newValue){
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
try {
return set.call(this, canReflect.convert(newValue, type));
} catch (error) {
var typeName = canReflect.getName(type[baseTypeSymbol]);
var message = newValue + ' is not of type ' + typeName + '. Property ' + prop + ' is using "type: ' + typeName + '". ';
message += 'Use "' + prop + ': type.convert(' + typeName + ')" to automatically convert values to ' + typeName + 's when setting the "' + prop + '" property.';
throw new Error(message);
}
}
//!steal-remove-end
return set.call(this, canReflect.convert(newValue, type));
};
}
Expand Down
20 changes: 20 additions & 0 deletions test/define-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ const QUnit = require("steal-qunit");
const { mixinObject } = require("./helpers");
const { hooks } = require("../src/define");
const canReflect = require("can-reflect");
const type = require('can-type');
const dev = require("can-test-helpers").dev;

QUnit.module("can-observable-mixin - define()");

Expand Down Expand Up @@ -188,3 +190,21 @@ QUnit.test("properties using value behavior reset when unbound", function(assert

assert.equal(obj.derivedProp, undefined, "value reset");
});

dev.devOnlyTest('On error include the name of the property that is being set', function(assert) {
class Person extends mixinObject() {
static get props() {
return {
age: type.check(Number)
};
}
}

var farah = new Person();

try {
farah.age = '4';
} catch (error) {
assert.equal(error.message, '4 is not of type Number. Property age is using "type: Number". Use "age: type.convert(Number)" to automatically convert values to Numbers when setting the "age" property.');
}
});

0 comments on commit 5c56ee7

Please sign in to comment.