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.
Error codes
Section titled “Error codes”| 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.
Catching errors
Section titled “Catching errors”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.
Every class throws MdgUtilsException (an InvalidArgumentException). Check errorCode.
use Mdgascar\MdgUtils\Ariary\Ariary;use Mdgascar\MdgUtils\ErrorCode;use Mdgascar\MdgUtils\MdgUtilsException;
try { Ariary::parse('1,500');} catch (MdgUtilsException $exception) { $exception->errorCode === ErrorCode::InvalidFormat; // true}Three ways to parse
Section titled “Three ways to parse”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; // falseif (!result.success) result.error.code; // 'UNKNOWN_OPERATOR'
tryParsePhoneNumber('031 12 345 67'); // undefineduse Mdgascar\MdgUtils\Phone\PhoneNumber;
PhoneNumber::parse('031 12 345 67'); // throws MdgUtilsException UNKNOWN_OPERATOR
$result = PhoneNumber::safeParse('031 12 345 67');$result->success; // false$result->error?->errorCode; // ErrorCode::UnknownOperator
PhoneNumber::tryParse('031 12 345 67'); // null