Custom Error Handlers (set_error_handler)
TL;DR
set_error_handler() lets you replace PHP's default error handling with a custom callback — essential for logging, alerting, and graceful degradation.
Explanation
PHP triggers errors via a global error handler. set_error_handler(callable $handler) replaces it for user-level errors (E_WARNING, E_NOTICE, E_USER_ERROR etc.) but cannot catch E_ERROR, E_PARSE, or E_CORE_ERROR — those still kill the script unless register_shutdown_function() is used. The callback receives ($errno, $errstr, $errfile, $errline). Always restore the previous handler with restore_error_handler() in tests. set_exception_handler() is the equivalent for uncaught exceptions.
Common Misconception
✗ set_error_handler() catches all errors — it cannot catch fatal errors (E_ERROR, E_PARSE). Use register_shutdown_function() + error_get_last() to handle those.
Why It Matters
Custom error handlers let you log errors to external systems, convert them to exceptions, and prevent sensitive paths from leaking in error messages.
Common Mistakes
- Forgetting to return true from the handler — PHP then executes the internal handler too.
- Not restoring the previous handler — breaks test isolation.
- Using set_error_handler() alone without register_shutdown_function() — misses fatal errors.
Code Examples
✗ Vulnerable
set_error_handler(function($errno, $errstr) {
// Silently ignores — errors disappear
});
✓ Fixed
set_error_handler(function(int $errno, string $errstr, string $errfile, int $errline): bool {
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
});
register_shutdown_function(function() {
$error = error_get_last();
if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR])) {
// Log fatal error before script dies
error_log("Fatal: {$error['message']} in {$error['file']}:{$error['line']}");
}
});
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
22 Mar 2026
Views
26
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 6
Perplexity 6
Unknown AI 3
Google 2
SEMrush 2
ChatGPT 1
Ahrefs 1
Also referenced
How they use it
crawler 18
crawler_json 1
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🟡 Medium
⚙ Fix effort: Low
⚡ Quick Fix
Register handler with set_error_handler(fn($errno,$errstr,$errfile,$errline) => throw new ErrorException($errstr,0,$errno,$errfile,$errline)) — then catch ErrorException everywhere.
📦 Applies To
PHP 5.0+
web
cli
queue-worker
🔍 Detection Hints
set_error_handler
Auto-detectable:
✓ Yes
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: High
False Positives: Low
✗ Manual fix
Fix: Medium
Context: Function
Tests: Update