×

php · level 3 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An exception can carry extra details, and even another exception.

A message is only text, but a form wants to know which field failed. Give your exception a constructor with an extra readonly property, then hand the message on with parent::__construct($message) so that getMessage() still works.

When a low-level error bubbles up, like a database complaint, it: catch it and throw your own clearer exception, passing the original as the third argument, as in new StorageFailed("...", 0, $e). The 0 is a number code. Later, getPrevious() hands the original back. Linked like this, they form an .

<?php
class InvalidField extends InvalidArgumentException {
    public function __construct(public readonly string $field, string $message) {
        parent::__construct($message);
    }
}
function checkEmail(string $email): void {
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        throw new InvalidField("email", "That email does not look right.");
    }
}
try {
    checkEmail("mia-at-example");
} catch (InvalidField $e) {
    echo "Field '$e->field': " . $e->getMessage() . "\n";
}

A form can now put each message beside the right box, because it knows $e->field.