Skip to content

Instantly share code, notes, and snippets.

@zlikavac32
Created October 1, 2018 14:02
Show Gist options
  • Select an option

  • Save zlikavac32/cb0969b64a7eb9e3f41fed655ada360e to your computer and use it in GitHub Desktop.

Select an option

Save zlikavac32/cb0969b64a7eb9e3f41fed655ada360e to your computer and use it in GitHub Desktop.
<?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