Skip to content

Error handling

Most validation failures throw specific errors. Catch the specific error when code needs to distinguish between invalid value categories.

typescript
import { Email, InvalidEmailError } from '@haskou/value-objects';

try {
  new Email('invalid');
} catch (error) {
  if (error instanceof InvalidEmailError) {
    // Invalid email format.
  }
}

Common errors

ErrorUsually thrown by
InvalidStringLengthErrorStringValueObject
InvalidPasswordErrorPassword
InvalidNumberErrorNumberValueObject
InvalidIntegerErrorInteger, Year, Day
InvalidPositiveNumberErrorPositiveNumber
InvalidEmailErrorEmail
InvalidColorErrorColor
InvalidLengthErrorIDs, keys, payloads
InvalidFormatErrorIDs, keys, payloads
InvalidHashErrorHash classes
InvalidDayErrorDay, CalendarDay, DayOfWeek
InvalidDayFormatErrorCalendarDay
InvalidHourErrorHour
InvalidMinutesErrorHour
InvalidTimestampIntervalErrorTimestampInterval
ValueNotInEnumErrorEnum subclasses
NullObjectErrorCalling a fake method on a null object

Pattern

typescript
function parseEmail(value: string): Email | null {
  try {
    return new Email(value);
  } catch (error) {
    if (error instanceof InvalidEmailError) {
      return null;
    }

    throw error;
  }
}

Keep catch blocks narrow. Broadly swallowing validation errors is how data quality goes to die quietly in production.

Released under the MIT License.