Skip to content

Instantly share code, notes, and snippets.

@krmgns
Created October 18, 2022 11:08
Show Gist options
  • Save krmgns/9dc23b42a2257f3871a95318d835067c to your computer and use it in GitHub Desktop.
Save krmgns/9dc23b42a2257f3871a95318d835067c to your computer and use it in GitHub Desktop.
Error handling in PHP
set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext = null) {
prs("here! $errstr");
});
class ErrorHelper {
var $lastError;
function setErrorHandler() {
$this->lastError = null;
set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext = null) {
$this->lastError = compact('errno', 'errstr', 'errfile', 'errline', 'errcontext');
});
}
function restoreErrorHandler() {
restore_error_handler();
}
function throwLastError($code = 0) {
if ($this->lastError) {
extract($this->lastError);
throw new \ErrorException($errstr, $code, $errno, $errfile, $errline);
}
}
}
$eh = new ErrorHelper();
$eh->setErrorHandler();
try {
@chdir("");
$eh->throwLastError();
} catch (\ErrorException $e) {
// prd($e);
} finally {
$eh->restoreErrorHandler();
}
var_dump($eh);
@chdir("");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment