Created
October 1, 2018 14:02
-
-
Save zlikavac32/cb0969b64a7eb9e3f41fed655ada360e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * In this example, we'd use it like throw new FileNotFoundException($missingFileName) | |
| * or throw new FileNotFoundException(sprintf("File not found")) or | |
| * throw new FileNotFoundException(sprintf("File %s not found", $missingFileName)) | |
| * which quickly leads to non-uniform messages and hard-to-process/recover exceptions. | |
| * | |
| * Is it possible to perhaps send nice e-mail message? | |
| */ | |
| class FileNotFoundException extends RuntimeException { | |
| } | |
| /** | |
| * In this example, to create an exception, we must always provide causing file | |
| * which will have uniform messages, and if this exception is caught, | |
| * we can easily access string that contains file which caused exception | |
| */ | |
| class FileNotFoundException extends RuntimeException { | |
| private $missingFileName; | |
| public function __construct(string $missingFileName, Throwable $previous = null) { | |
| parent::__construct(sprintf('File "%s" not found'm $missingFileName), 0, $previous); | |
| $this->missingFileName = $missingFileName; | |
| } | |
| public function missingFileName(): string { | |
| return $this->missingFileName; | |
| } | |
| } | |
| /** | |
| * Every exceptions has a reason for being thrown. PHP can not know the reason | |
| * so he offers most general solution with a single message parameter. | |
| * But by exceptions being classes, it also allows each new exception to be properly defined. | |
| * | |
| * So when I decide to create an exception class, I extend proper parent exception | |
| * and provide arguments that should be provided (since they are the reason or context). | |
| * | |
| * Arguments that you'd use in sprintf are probably gonna end up as arguments to the | |
| * constructor. | |
| * | |
| * Also, it's important to have a proper tree, and not just extend Exception. | |
| * That way sub classes can be caught, and error recovery becomes more robust. | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment