Skip to content

Commit b16deb4

Browse files
committed
Add a type table for function argument mismatch error messages
1 parent 54478af commit b16deb4

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

jmespath.js

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,18 @@
140140
var TYPE_NULL = 7;
141141
var TYPE_ARRAY_NUMBER = 8;
142142
var TYPE_ARRAY_STRING = 9;
143+
var TYPE_NAME_TABLE = {
144+
0: 'number',
145+
1: 'any',
146+
2: 'string',
147+
3: 'array',
148+
4: 'object',
149+
5: 'boolean',
150+
6: 'expression',
151+
7: 'null',
152+
8: 'Array<number>',
153+
9: 'Array<string>'
154+
};
143155

144156
var TOK_EOF = "EOF";
145157
var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier";
@@ -1237,11 +1249,16 @@
12371249
}
12381250
}
12391251
if (!typeMatched) {
1252+
var expected = currentSpec
1253+
.map(function(typeIdentifier) {
1254+
return TYPE_NAME_TABLE[typeIdentifier];
1255+
})
1256+
.join(',');
12401257
throw new Error("TypeError: " + name + "() " +
12411258
"expected argument " + (i + 1) +
1242-
" to be type " + currentSpec +
1243-
" but received type " + actualType +
1244-
" instead.");
1259+
" to be type " + expected +
1260+
" but received type " +
1261+
TYPE_NAME_TABLE[actualType] + " instead.");
12451262
}
12461263
}
12471264
},

test/jmespath.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ describe('tokenize', function() {
160160
]
161161
);
162162
});
163+
163164
});
164165

165166

@@ -215,3 +216,19 @@ describe('strictDeepEqual', function() {
215216
{a: {b: [1, 4]}}), false);
216217
});
217218
});
219+
220+
describe('search', function() {
221+
it(
222+
'should throw a readable error when invalid arguments are provided to a function',
223+
function() {
224+
try {
225+
jmespath.search([], 'length(`null`)');
226+
} catch (e) {
227+
assert(e.message.search(
228+
'expected argument 1 to be type string,array,object'
229+
), e.message);
230+
assert(e.message.search('received type null'), e.message);
231+
}
232+
}
233+
);
234+
});

0 commit comments

Comments
 (0)