Error Handling and Exception Handling in PHP: Best Practices πŸš€

Error Handling and Exception Handling in PHP: Best Practices πŸš€

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! πŸŽ‰πŸš€

Leave a Reply