Skip to content

Instantly share code, notes, and snippets.

@jfensign
Created April 7, 2012 23:29
Show Gist options
  • Save jfensign/2332824 to your computer and use it in GitHub Desktop.
Save jfensign/2332824 to your computer and use it in GitHub Desktop.
Extending PHP's Exception Class
<?php
//AppException.php
class AppException extends Exception {
public function __construct($msg="", $code = 0) {
/*
PHP's Exception class will handle all
of the necessary validation
*/
parent::__construct($msg, $code);
}
public function __toString() {
return "[{$this->code}]:
<span class='error'>
{$this->message}
</span>
<br />" .
var_dump($this);
}
//renders view file
private static function renderExceptionView($path, $vars) {
//check if $path points to an existing file
if(!file_exists($path)) {
echo "Specified Template Does not Exist";
}
else {
/*
takes an associative array and uses
the array's keys to create variables and
the array's values as their respective values
*/
if(is_array($vars) && count($vars) > 0) {
//extract array elements and prefix duplicates with AppException
extract($vars, EXTR_PREFIX_SAME, "AppException_");
//include the file
include_once($path);
}
}
}
//handle 404 example
public function get404($view = NULL, array $viewVars = NULL) {
//set status
header("Status: 404 Not Found");
//set content type
header("Content-type: text/html");
//call static function renderExceptionView to load your page
self::renderExceptionView($view, $viewVars);
}
}
<?php
//How To Instantiate
$error = new AppException();
$error->get404("PATHTOVIEW/404_view.inc.php", array("title" => "Page Not Found"));
// OR
try {
//something to try
} catch(AppException $e) {
$e->get404("PATHTOVIEW/404_view.inc.php", array("title" => "Page Not Found"));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment