Skip to content
← Back to Snippets
Code

Custom Error Handler

Registers a temporary custom error handler that captures safe error details into an array and restores the previous handler.

Purpose

Registers a temporary custom error handler that captures safe error details into an array and restores the previous handler.

Snippet details

ContextError HandlingLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Custom Error Handler.
 *
 * Purpose:
 * Captures user-level PHP errors into a local log array.
 *
 * @return array Captured error entries.
 */
function ogSnippetCustomErrorHandler(): array {
	$captured_errors = array();

	set_error_handler(function ($severity, $message, $file, $line) use (&$captured_errors) {
		$captured_errors[] = array(
			'severity' => (int) $severity,
			'message' => (string) $message,
			'file' => basename((string) $file),
			'line' => (int) $line
		);

		return true;
	});

	trigger_error('Stargate telemetry warning captured.', E_USER_WARNING);
	restore_error_handler();

	return $captured_errors;
}

$error_log = ogSnippetCustomErrorHandler();

echo 'Captured errors: '.count($error_log);