From a0bba9632bc0638dc0ea95b8a6414790279e4bdd Mon Sep 17 00:00:00 2001 From: jxom Date: Sat, 7 Sep 2024 11:35:46 +1000 Subject: [PATCH] chore: added extra error handling to unit parsing --- src/errors/unit.ts | 12 ++++++++++++ src/utils/unit/parseUnits.ts | 4 ++++ 2 files changed, 16 insertions(+) create mode 100644 src/errors/unit.ts diff --git a/src/errors/unit.ts b/src/errors/unit.ts new file mode 100644 index 0000000000..a98b5f21be --- /dev/null +++ b/src/errors/unit.ts @@ -0,0 +1,12 @@ +import { BaseError } from './base.js' + +export type InvalidDecimalNumberErrorType = InvalidDecimalNumberError & { + name: 'InvalidDecimalNumberError' +} +export class InvalidDecimalNumberError extends BaseError { + constructor({ value }: { value: string }) { + super(`Number \`${value}\` is not a valid decimal number.`, { + name: 'InvalidDecimalNumberError', + }) + } +} diff --git a/src/utils/unit/parseUnits.ts b/src/utils/unit/parseUnits.ts index c8e7010de2..8f62eaef37 100644 --- a/src/utils/unit/parseUnits.ts +++ b/src/utils/unit/parseUnits.ts @@ -1,3 +1,4 @@ +import { InvalidDecimalNumberError } from '../../errors/unit.js' import type { ErrorType } from '../../errors/utils.js' export type ParseUnitsErrorType = ErrorType @@ -14,6 +15,9 @@ export type ParseUnitsErrorType = ErrorType * // 420000000000n */ export function parseUnits(value: string, decimals: number) { + if (!/^(-?)([0-9]*)\.?([0-9]*)$/.test(value)) + throw new InvalidDecimalNumberError({ value }) + let [integer, fraction = '0'] = value.split('.') const negative = integer.startsWith('-')