Custom PHP error handlers decide how recoverable runtime errors are reported and logged.
What It Does
Custom PHP error handlers decide how recoverable runtime errors are reported and logged. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
set_error_handler(function (int $level, string $message): bool { echo 'Handled warning'; return true; });
trigger_error('Example warning', E_USER_WARNING);
restore_error_handler();
Example 2: Another Case
Examine the edge case and the observable result.
<?php
register_shutdown_function(function (): void { $last = error_get_last(); if ($last !== null) error_log('Shutdown code: ' . $last['type']); });
echo 'Shutdown handler registered';
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
set_exception_handler(function (Throwable $e): void { error_log(get_class($e)); });
restore_exception_handler();
echo 'Handler restored';
Important Behavior and Edge Cases
An error handler does not catch every fatal error or Throwable; restore handlers after scoped use.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Custom Error Handlers Explained | Custom PHP error handlers decide how recoverable runtime errors are reported and logged. |
| Related approach | Use set_exception_handler() for uncaught exceptions and shutdown functions for final fatal-error diagnostics. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Custom Error Handlers Explained | An error handler does not catch every fatal error or Throwable; restore handlers after scoped use. |
| Assuming a related mechanism has the same behavior | Use set_exception_handler() for uncaught exceptions and shutdown functions for final fatal-error diagnostics. |
Key Takeaways
- Custom PHP error handlers decide how recoverable runtime errors are reported and logged.
- An error handler does not catch every fatal error or Throwable; restore handlers after scoped use.
- Use set_exception_handler() for uncaught exceptions and shutdown functions for final fatal-error diagnostics.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.