Skip to content

Instantly share code, notes, and snippets.

@Ferreiramg
Created July 28, 2013 17:47
Show Gist options
  • Save Ferreiramg/6099432 to your computer and use it in GitHub Desktop.
Save Ferreiramg/6099432 to your computer and use it in GitHub Desktop.
set_error_handler(), custom class E_USER_*
<?php
class errorHandler {
public function __construct() {
$_t = $this;
set_error_handler(
function ($error, $msg, $file, $line) use ($_t) {
switch ($error) {
// ++$var
case E_NOTICE:
return $_t->writeCustomLog($msg, $file, $line, 'E_NOTICE');
//For Trigger Errors
case E_USER_NOTICE:
return $_t->writeCustomLog($msg, $file, $line, 'E_USER_NOTICE');
case E_USER_WARNING:
return $_t->writeCustomLog($msg, $file, $line, 'E_USER_WARNING');
//E_*
default :
$_t->writeCustomLog($msg, $file, $line, 'FATAL_ERROR');
throw new \Exception($msg . '! See Log for more details');
}
}
);
}
private function writeCustomLog($msg, $file, $line, $type = "E_USER_ERROR") {
return file_put_contents(
__TEMP__ . DIRECTORY_SEPARATOR . 'myerrorLog.log',
sprintf("[%s][%s] %s -> %s: %s", $type, date('now'), $file, $line, $msg),
FILE_APPEND
);
}
function __destruct() {
restore_error_handler();
}
}
//testando
ini_set('display_errors', 1); // comprovando eficiencia.
define('__TEMP__', sys_get_temp_dir()); //pega o diretorio Temp do server.
function __error($type = E_USER_WARNING) {
trigger_error('Erro Simulado', $type);
return true;
}
try {
//error_handler Init
$error = new errorHandler();
++$v; //continue script E_NOTICE not FATAL
var_dump(__error()); // continue script E_WARNING not FATAL
echo '<br>', PHP_EOL;
var_dump(__error(E_USER_ERROR)); //show Exception FATAL_ERROR
echo 'Not Show'; //go to catch
} catch (Exception $e) {
echo $e->getMessage();
}
//unset($error); //restore_error_handler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment