Skip to content

Instantly share code, notes, and snippets.

@ixqbar
Created September 4, 2018 02:36
Show Gist options
  • Save ixqbar/70d9a93dfb65d26bbda6411f03cb34b6 to your computer and use it in GitHub Desktop.
Save ixqbar/70d9a93dfb65d26bbda6411f03cb34b6 to your computer and use it in GitHub Desktop.
php-error
function registerErrorHandler(callable $callable)
{
	set_error_handler(function (int $err_no, string $err_msg, string $err_file = '', int $err_line = 0, array $err_context = []) use ($callable) {
		call_user_func($callable, sprintf('%s in file %s at line %s', $err_msg, $err_file, $err_line));
	});

	set_exception_handler(function (Throwable $e) use ($callable) {
		call_user_func($callable, $e->getMessage() . ',FILE:' . $e->getFile() . ',LINE:' . $e->getLine() . ',Trace:' . $e->getTraceAsString());
	});

	register_shutdown_function(function () use ($callable) {
		try {
			$last_error = error_get_last();
			if (empty($last_error)) {
				return;
			}
			call_user_func($callable, '[' . $last_error['type'] . ']' . $last_error['message'] . ' in ' . $last_error['file'] . ' at ' . $last_error['line'] . ' line');
		} catch (Throwable $e) {
			call_user_func($callable, $e->getMessage() . ',FILE:' . $e->getFile() . ',LINE:' . $e->getLine() . ',Trace:' . $e->getTraceAsString());
		}
	});
}

registerErrorHandler(function ($message) {
	echo $message . PHP_EOL;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment