Skip to content

Instantly share code, notes, and snippets.

@Nilpo
Last active May 10, 2020 09:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilpo/4312309 to your computer and use it in GitHub Desktop.
Save Nilpo/4312309 to your computer and use it in GitHub Desktop.
If you intend on creating a lot of custom exceptions, I've created an interface and an abstract exception class that ensures that all parts of PHP's built-in Exception class are preserved in child classes. It also properly pushes all information back to the parent constructor ensuring that nothing is lost. This allows you to quickly create new e…
<?php
/*
* This code is free software; you can use it, redistribute it, and/or modify as you wish.
* This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY - implied or otherwise.
* This code is distributed "as is." All risk and cost are assumed by the user of the code and not the creator thereof.
* If you wish to give attribution, the original creator is Robert "Nilpo" Dunham (devnilpo@gmail.com)
*/
interface IException
{
/* Protected methods inherited from Exception class */
public function getMessage(); // Exception message
public function getCode(); // User-defined Exception code
public function getFile(); // Source filename
public function getLine(); // Source line
public function getTrace(); // An array of the backtrace()
public function getTraceAsString(); // Formated string of trace
/* Overrideable methods inherited from Exception class */
public function __toString(); // formatted string for display
public function __construct($message = null, $code = 0);
}
abstract class CustomException extends Exception implements IException
{
protected $message = 'Unknown exception'; // Exception message
private $string; // Unknown
protected $code = 0; // User-defined exception code
protected $file; // Source filename of exception
protected $line; // Source line of exception
private $trace; // Unknown
public function __construct($message = null, $code = 0)
{
if (!$message) {
throw new $this('Unknown '. get_class($this));
}
parent::__construct($message, $code);
}
public function __toString()
{
return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
. "{$this->getTraceAsString()}";
}
}
?>
<?php
require 'CustomException.php';
class TestException extends CustomException {}
?>
<?php
require 'CustomException.php';
class TestException extends CustomException {}
function exceptionTest()
{
try {
throw new TestException();
}
catch (TestException $e) {
echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n";
}
catch (Exception $e) {
echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
}
}
echo '<pre>' . exceptionTest() . '</pre>';
?>
@marcosrocha85
Copy link

Are $string and $trace been used somewhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment