Skip to content

Instantly share code, notes, and snippets.

@bvarent
Created June 17, 2016 14: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 bvarent/f03c87eb029c6eb3ef42d67d1f72fa14 to your computer and use it in GitHub Desktop.
Save bvarent/f03c87eb029c6eb3ef42d67d1f72fa14 to your computer and use it in GitHub Desktop.
add setter methods to a PHP Exception
<?php
namespace My\Exception;
use Exception;
use ReflectionProperty;
/**
* Fluent cq chaining setter methods for an Exception class.
* To set or modify an Exception's properties after construction.
*
* Although it is a little flaky to make these one-time-set properties alterable,
* it is usable to prevent having a `$code` and `$previous` argument for all your
* {@link http://rosstuck.com/formatting-exception-messages/ custom exception messages}.
* <code><?php
* class MyCustomException extends \Exception {
* use TFluentExceptionMethods;
* static function someExceptionalSituation() {
* return new self("Something specific went wrong.");
* }
* }
* function someUnreliableFunction() {
* try {
* unexistingMethod();
* } catch (\Exception $e) {
* throw MyCustomException::someExceptionalSituation()->setPrevious($e);
* }
* }
* </code>
*/
trait TExceptionSetterMethods
{
/**
* @param string $message
* @return static
*/
public function setMessage($message)
{
$this->message = (string)$message;
return $this;
}
/**
* @param string $code
* @return static
*/
public function setCode($code)
{
$this->code = (int)$code;
return $this;
}
/**
* @param Exception $previous
* @return static
*/
public function setPrevious(Exception $previous)
{
// 'previous' property is private to the Exception class.
$previousProp = new ReflectionProperty(Exception::class, "previous");
$previousProp->setAccessible(true);
$previousProp->setValue($this, $previous);
$previousProp->setAccessible(false);
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment