Mastering Error Handling in PHP - Types, Tools & Best Practices
Errors are inevitable - whether you're writing a simple script or a full-stack web application. But how you handle those errors can mean the difference between a crash and a graceful recovery.
In this post, we’ll explore how PHP handles errors, what’s changed in recent versions,and how to properly debug, display, and log errors in production.
Why Error Handling Matters
Every developer makes mistakes - and sometimes, so does the server. Whether it’s a syntax mistake, missing file, or failed database connection, robust error handling:
- Prevents your app from crashing
- Helps you debug efficiently
- Improves security (no sensitive data exposed)
- Creates a better user experience
Types of Errors in PHP
PHP handles several categories of errors:
| Type | Description |
|---|---|
| Parse Error | Syntax error - prevents execution |
| Fatal Error | Stops script immediately (e.g., calling undefined function) |
| Warning | Non-fatal - continues execution (e.g., missing file) |
| Notice | Minor issues (e.g., using undefined variable) |
| Throwable (PHP 7+) | Errors that can be caught using try-catch |
Enabling Error Reporting in Development
To see all errors while coding:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Never use this in production! It may reveal server paths, DB credentials, or stack traces.
Using try...catch for Exception Handling
PHP supports object-oriented exception handling:
try {
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
} catch (PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
}
Use it when:
- Working with databases
- File handling
- External APIs
- Custom exception logic
Logging Errors to a File
Instead of showing errors to users, log them for yourself:
ini_set("log_errors", 1);
ini_set("error_log", "/path/to/php-error.log");
This is crucial in production environments. Use tools like Monolog for structured logging in modern apps.
Creating Custom Error Handlers
You can define your own logic when an error occurs:
function myErrorHandler($errno, $errstr, $errfile, $errline) {
error_log("Error [$errno] in $errfile:$errline → $errstr");
// Optionally display a user-friendly message
}
set_error_handler("myErrorHandler");
For exceptions:
set_exception_handler(function($e) {
error_log("Uncaught exception: " . $e->getMessage());
});
Why You Should Never Display Raw Errors in Production
When your app throws an error, it might expose:
- Server file paths
- Internal functions or logic
- Database credentials
- Session variables
Always:
- Disable
display_errors - Enable logging
- Show a generic fallback message (e.g.,“Something went wrong.”)
Tools for Modern Error Handling
- Monolog: Advanced logging (to file, Slack, email, etc.)
- Whoops: Pretty error pages for development
- Laravel Exception Handler: Centralized, customizable error control
- Sentry: Cloud-based error monitoring (with PHP SDK)
Bonus - Convert Errors to Exceptions
Turn all standard errors into exceptions (for unified handling):
set_error_handler(function($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
});
Then catch them with try...catch.
Best Practices Summary
| Do's | Don'ts |
|---|---|
Enable
display_errors in dev only |
Show full errors in production |
Use error_log() or Monolog |
Ignore error logs |
| Catch exceptions properly | Suppress errors with @ operator |
| Centralize error handling | Scatter try-catch everywhere |
| Set custom handlers | Rely on default behaviors blindly |
Final Thoughts
Error handling in PHP has evolved a lot over the years. With tools like exception classes, custom handlers, and modern frameworks, you can build apps that fail gracefully and log intelligently.
Take the time to plan your error handling - because errors will happen. The question is: will your app be ready?