Skip to content

Instantly share code, notes, and snippets.

@koriym
Last active July 8, 2022 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koriym/af8bdc3ae2cf0e45b4ed923a073cf18d to your computer and use it in GitHub Desktop.
Save koriym/af8bdc3ae2cf0e45b4ed923a073cf18d to your computer and use it in GitHub Desktop.
PHP Semantic Exception
<?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