Skip to content

Commit d330b64

Browse files
committed
Bugfix: Interpreter conversion of string to number should throw on NaN #27788 (#50063)
1 parent ebb090d commit d330b64

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

src/plugins/expressions/public/expression_types/number.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
* under the License.
1818
*/
1919

20+
import { i18n } from '@kbn/i18n';
2021
import { ExpressionType } from '../types';
2122
import { Datatable } from './datatable';
2223
import { Render } from './render';
@@ -28,7 +29,20 @@ export const number = (): ExpressionType<typeof name, number> => ({
2829
from: {
2930
null: () => 0,
3031
boolean: b => Number(b),
31-
string: n => Number(n),
32+
string: n => {
33+
const value = Number(n);
34+
if (Number.isNaN(value)) {
35+
throw new Error(
36+
i18n.translate('expressions_np.types.number.fromStringConversionErrorMessage', {
37+
defaultMessage: 'Can\'t typecast "{string}" string to number',
38+
values: {
39+
string: n,
40+
},
41+
})
42+
);
43+
}
44+
return value;
45+
},
3246
},
3347
to: {
3448
render: (value: number): Render<{ text: string }> => {
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
* Licensed to Elasticsearch B.V. under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch B.V. licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
import { number } from '../number';
21+
22+
describe('number', () => {
23+
it('should fail when typecasting not numeric string to number', () => {
24+
expect(() => number().from!.string('123test', {})).toThrowErrorMatchingInlineSnapshot(
25+
`"Can't typecast \\"123test\\" string to number"`
26+
);
27+
});
28+
});

0 commit comments

Comments
 (0)