Skip to content

Commit

Permalink
chore: added extra error handling to unit parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
jxom committed Sep 7, 2024
1 parent 615d39c commit a0bba96
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/errors/unit.ts
Original file line number Diff line number Diff line change
@@ -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',
})
}
}
4 changes: 4 additions & 0 deletions src/utils/unit/parseUnits.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { InvalidDecimalNumberError } from '../../errors/unit.js'
import type { ErrorType } from '../../errors/utils.js'

export type ParseUnitsErrorType = ErrorType
Expand All @@ -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('-')
Expand Down

0 comments on commit a0bba96

Please sign in to comment.