Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Turn php errors into exceptions; Codeigniter's implementation, but can be adapted for every other project.
<?php
# Error handler
function custom_error_handler($errno, $errstr, $errfile, $errline)
{
if (AppSettings::$env == 'dev')
{
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
else
{
custom_exception_handler(new ErrorException($errstr, 0, $errno, $errfile, $errline));
}
}
# Shutdown method to find out whether shutdown was because of any fatal error
function fatal_error_shutdown_handler()
{
$last_error = error_get_last();
if ($last_error['type'] === E_ERROR || $last_error['type'] === E_PARSE)
{
custom_exception_handler(new ErrorException($last_error['message'], 0, 0, $last_error['file'], $last_error['line']));
}
}
# Exception handler
function custom_exception_handler($exception)
{
$post = $_POST;
unset($post['some confidential variable that shouldn\'t be logged']);
$message = (string)$exception;
get_instance()->db->query(
'INSERT INTO system_errors (type, request, post_data, errors, website) VALUES (?, ?, ?, ?, ?)',
array('php', print_r($_SERVER, TRUE), print_r($post, TRUE), $message, 'www')
);
if (AppSettings::$env == 'dev')
{
echo "<br />\n" . str_replace("\n", "<br />\n", $message) . "<br />\n";
}
}
# Register handlers
set_error_handler('custom_error_handler', E_ALL);
set_exception_handler('custom_exception_handler');
register_shutdown_function('fatal_error_shutdown_handler');
?>
-- PostgreSQL --
CREATE TABLE "system_errors" (
"id" serial NOT NULL,
"type" text NOT NULL DEFAULT ''::text,
"request" text NOT NULL DEFAULT ''::text,
"post_data" text NOT NULL DEFAULT ''::text,
"errors" text NOT NULL DEFAULT ''::text,
"website" varchar(15) NOT NULL DEFAULT ''::character varying,
"created" timestamp NOT NULL DEFAULT now()
)
WITH (OIDS=FALSE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment