Aller au contenu
GitHub

Getting started

Parsing and errors

Every mdg-utils function rejects bad input with the same four error codes in every language. Parsers come in three forms, so you choose between exceptions, error codes and plain absence.

Ce contenu n’est pas encore disponible dans votre langue.

Code Meaning
INVALID_TYPE The input has the wrong type, e.g. a number where text is expected
OUT_OF_RANGE The value is outside what the module supports
INVALID_FORMAT Text that cannot be read, e.g. 1,500 as an amount
UNKNOWN_OPERATOR A mobile prefix not assigned to any Malagasy operator

The codes are defined once in the spec, so a browser and a PHP server reject the same input with the same code.

Every package throws MdgError. Check error.code.

import { MdgError, parseAriary } from '@mdgascar/ariary';
try {
parseAriary('1,500');
} catch (error) {
if (error instanceof MdgError) error.code; // 'INVALID_FORMAT'
}

instanceof MdgError works across packages and across duplicated copies of a package.

Functions that read text typed by users — phone numbers and Ariary amounts — come in three forms.

Form On bad input Use it when
parse throws bad input is a bug in your code
safeParse returns { success: false, error } you show the user why the input was rejected
tryParse returns nothing (undefined / null) you only need to know whether it worked
import { parsePhoneNumber, safeParsePhoneNumber, tryParsePhoneNumber } from '@mdgascar/phone';
parsePhoneNumber('031 12 345 67'); // throws MdgError UNKNOWN_OPERATOR
const result = safeParsePhoneNumber('031 12 345 67');
result.success; // false
if (!result.success) result.error.code; // 'UNKNOWN_OPERATOR'
tryParsePhoneNumber('031 12 345 67'); // undefined