Errors happen! But instead of displaying ugly PHP error messages on a live site, we need to handle them gracefully.
π― In this guide, youβll learn:
β
Different types of PHP errors
β
How to use error reporting levels
β
Handling errors with try...catch
blocks
β
Logging errors instead of displaying them
β
Building a custom error handler
β
A real-world error-handling mini project
Letβs fix those errors like a pro! π
1οΈβ£ Types of Errors in PHP
PHP has three major types of errors:
Error Type | Description |
---|---|
Notices | Minor issues (e.g., using an undefined variable). |
Warnings | More serious but the script continues (e.g., file not found). |
Fatal Errors | Critical errors that stop execution (e.g., calling a missing function). |
π₯ Example: Understanding PHP Errors
<?php
echo $undefined_var; // Notice: Undefined variable
include("missing_file.php"); // Warning: File not found
non_existent_function(); // Fatal Error: Function does not exist
?>
π‘ We need proper error handling to prevent these from breaking our app!
2οΈβ£ Enabling Error Reporting for Development
πΉ To see all errors and warnings, enable full error reporting in development mode.
Add this to your PHP script:
error_reporting(E_ALL);
ini_set("display_errors", 1);
π₯ Why use this?
β
Helps debug issues faster.
β
Shows all errors and warnings.
3οΈβ£ Handling Errors with try...catch
π‘ Exceptions allow you to catch and handle errors instead of stopping execution.
Example: Handling Errors Gracefully
<?php
function divide($a, $b) {
if ($b == 0) {
throw new Exception("Cannot divide by zero!");
}
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>
π₯ Whatβs happening?
β
If $b == 0
, it throws an exception.
β
The catch
block handles the error instead of crashing the script.
4οΈβ£ Logging Errors Instead of Displaying Them
On a live site, we shouldnβt show errors to users. Instead, log them to a file.
Step 1: Create a Log File
touch error_log.txt
chmod 666 error_log.txt
Step 2: Configure PHP to Log Errors
error_reporting(E_ALL);
ini_set("log_errors", 1);
ini_set("error_log", "error_log.txt");
π₯ Now errors are logged to error_log.txt
instead of being displayed! π―
5οΈβ£ Custom Error Handling in PHP
π‘ Instead of using PHPβs default error messages, letβs create a custom error handler.
Example: Custom Error Handler
<?php
function customErrorHandler($errno, $errstr, $errfile, $errline) {
$error_message = "[ERROR $errno] $errstr in $errfile on line $errline\n";
error_log($error_message, 3, "error_log.txt"); // Log errors to file
echo "Oops! Something went wrong. Please try again later.";
}
// Set custom error handler
set_error_handler("customErrorHandler");
// Trigger an error
echo $undefined_var; // Undefined variable
?>
π₯ Whatβs happening?
β
Logs errors to error_log.txt
.
β
Displays a friendly error message instead of PHPβs ugly errors.
6οΈβ£ Using set_exception_handler()
for Uncaught Exceptions
π‘ By default, uncaught exceptions stop execution. Letβs handle them better.
Example: Global Exception Handler
<?php
function globalExceptionHandler($exception) {
$error_message = "[EXCEPTION] " . $exception->getMessage() . "\n";
error_log($error_message, 3, "error_log.txt"); // Log exception
echo "Oops! Something went wrong.";
}
// Set exception handler
set_exception_handler("globalExceptionHandler");
// Trigger an exception
throw new Exception("This is a test exception!");
?>
π₯ Whatβs happening?
β
Handles uncaught exceptions globally.
β
Logs them instead of crashing the site.
7οΈβ£ Creating a Complete Error Handling System
π Letβs build a fully functional error-handling system with:
β
Logging to a file
β
Custom error messages
β
Handling fatal errors
1οΈβ£ Create error_handler.php
<?php
class ErrorHandler {
public static function handleErrors($errno, $errstr, $errfile, $errline) {
$error_message = "[ERROR] $errstr in $errfile on line $errline\n";
error_log($error_message, 3, "error_log.txt");
echo "An error occurred. Please try again later.";
}
public static function handleExceptions($exception) {
$error_message = "[EXCEPTION] " . $exception->getMessage() . "\n";
error_log($error_message, 3, "error_log.txt");
echo "An unexpected error occurred. Please try again.";
}
public static function handleShutdown() {
$error = error_get_last();
if ($error !== null) {
$error_message = "[FATAL ERROR] {$error['message']} in {$error['file']} on line {$error['line']}\n";
error_log($error_message, 3, "error_log.txt");
}
}
}
// Register error handlers
set_error_handler(["ErrorHandler", "handleErrors"]);
set_exception_handler(["ErrorHandler", "handleExceptions"]);
register_shutdown_function(["ErrorHandler", "handleShutdown"]);
?>
2οΈβ£ Test Error Handling in index.php
<?php
require "error_handler.php";
// Trigger a notice
echo $undefined_var;
// Trigger an exception
throw new Exception("Something went wrong!");
// Trigger a fatal error
non_existent_function();
?>
π₯ What happens?
β
Logs all errors, exceptions, and fatal errors.
β
Displays friendly error messages to users.
π Final Thoughts
Now you can handle errors like a pro!
β
Use try...catch
for exceptions
β
Log errors instead of displaying them
β
Create custom error handlers
β
Handle fatal errors gracefully
π Next: Session Management in PHP
Happy coding! ππ