An exception with its own name

Exercise 9 of 9 in chapter 5 · 150 XP · 4 objectives checked by tests

Topics covered: Inheritanceextendsparent::Custom exceptionException

Odette's nephew is worried. The front controller catches every exception: the day the gazette has a database and that database breaks down, readers will see “Lost in the post” instead of a real error, and nobody will go looking for the problem. We need a separate exception that means “this article does not exist”, and we should catch only that one.

Your mission

  1. In src/Contenu/ArticleIntrouvable.php, declare the class ArticleIntrouvable (ArticleNotFound), which inherits from PHP's Exception class: class ArticleIntrouvable extends Exception, with use Exception; below the namespace.
  2. Its constructor receives the slug (public readonly string $slug) and passes the message No article has the slug “{$slug}”., with the slug it received, to parent::__construct().
  3. In Redaction::article(), throw it instead of the Exception: throw new ArticleIntrouvable($slug);.
  4. In the front controller, catch (Exception) becomes catch (ArticleIntrouvable). Import it at the top of the file with use Gazette\Contenu\ArticleIntrouvable;: a catch on a class PHP doesn't know catches nothing, without any warning.

Reminder

extends creates a child class: ArticleIntrouvable gets everything Exception has (the message, getMessage(), the line where it was thrown…), and adds its slug to it. An ArticleIntrouvable is an Exception: a catch (Exception) would catch it too. But catch (ArticleIntrouvable) catches only that one, and lets the others through.

The child's constructor replaces the parent's. So that the message is still stored, the child calls the parent's constructor itself, with parent::__construct($message).