Last active
July 8, 2022 04:52
-
-
Save koriym/af8bdc3ae2cf0e45b4ed923a073cf18d to your computer and use it in GitHub Desktop.
PHP Semantic Exception
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 | |
namespace Application; | |
$fileName = '/not-writable'; | |
// Human-only readable exceptions | |
// throw new \RuntimeException("{$fileName} is not writable."); | |
// Semantic exceptions | |
throw new FileNotWritableException($fileName); | |
class FileNotWritableException extends RuntimeException | |
{ | |
public function __construct( | |
public readonly string $fileName | |
) | |
{ | |
// You can build the properties you want to log here. | |
parent::__construct(); | |
} | |
} | |
/** | |
* Base exception | |
*/ | |
class RuntimeException extends \RuntimeException | |
{ | |
public function __construct() | |
{ | |
$message = ''; | |
foreach ($this as $key => $value) { // @phpstan-ignore-line | |
if (in_array($key, ['code', 'message', 'file', 'line'])) { | |
continue; | |
} | |
$message .= "{$key}: {$value} "; | |
} | |
parent::__construct($message); | |
} | |
} | |
// Pros | |
// | |
// * Minimizes caller code | |
// * Ensures exception identity | |
// * Can reach the code from a specific exception in the IDE | |
// * Generate messages to ensure compatibility | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment