PHP Error System

Back

Loading concept...

🛡️ PHP Error Handling: Your Code’s Safety Net

The Story of the Watchful Guardian

Imagine you’re playing a video game. You have a health bar that shows when you’re hurt. Without it, you’d never know you’re about to lose!

PHP’s Error System is exactly like that health bar. It watches your code, tells you when something goes wrong, and helps you fix it before disaster strikes.

Let’s meet the guardians of your PHP code!


🎯 What We’ll Learn

graph TD A["Error Handling"] --> B["Error Types & Levels"] A --> C["Error Reporting"] A --> D["Custom Error Handlers"] A --> E["Global Exception Handler"] A --> F["Error vs Exception"]

1️⃣ Error Types and Levels

Think of Errors Like Warning Signs

Imagine you’re driving a car. Different warning lights mean different things:

Warning Light What It Means PHP Error Type
🟡 Low Fuel “Hey, fill up soon!” E_NOTICE
🟠 Check Engine “Something’s off!” E_WARNING
🔴 Engine Dead “STOP! Won’t work!” E_ERROR

PHP’s Error Levels Explained

Level 1: Notices (E_NOTICE) - Gentle Reminders

<?php
// Using a variable that doesn't exist
echo $name;
// Notice: Undefined variable $name
// Code keeps running!

Level 2: Warnings (E_WARNING) - Yellow Flags

<?php
// Trying to open a file that's missing
$file = fopen("ghost.txt", "r");
// Warning: file doesn't exist
// Code keeps running, but be careful!

Level 3: Fatal Errors (E_ERROR) - Red Alert!

<?php
// Calling a function that doesn't exist
callMagicFunction();
// Fatal error: Function not found
// Code STOPS here!

Level 4: Parse Errors (E_PARSE) - Spelling Mistakes

<?php
// Missing semicolon!
echo "Hello"  // ← forgot ;
echo "World";
// Parse error: syntax error
// Code won't even start!

📊 Error Levels Quick Chart

Level Constant Stops Code? How Serious?
Notice E_NOTICE No 🟢 Low
Warning E_WARNING No 🟡 Medium
Fatal E_ERROR Yes 🔴 Critical
Parse E_PARSE Yes 🔴 Critical

2️⃣ Error Reporting

Telling PHP What to Watch

Think of error reporting like a security camera. You choose what it should watch!

Turn On All Cameras (See Everything)

<?php
// Show me ALL errors - perfect for coding
error_reporting(E_ALL);

Turn Off All Cameras (See Nothing)

<?php
// Hide all errors - for finished websites
error_reporting(0);

Watch Only Red Alerts

<?php
// Only show fatal errors and warnings
error_reporting(E_ERROR | E_WARNING);

Showing Errors on Screen

<?php
// While building: SHOW errors
ini_set('display_errors', 1);

// On live website: HIDE errors
ini_set('display_errors', 0);

🔑 Golden Rule

While Coding: Show all errors On Live Site: Hide errors, log them instead

<?php
// Perfect setup for development
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Perfect setup for production
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'errors.log');

3️⃣ Custom Error Handlers

Be the Boss of Your Errors

Normally, PHP handles errors its way. But you can take control!

Think of it like hiring your own security guard instead of using the default one.

Step 1: Create Your Handler

<?php
function myErrorGuard($level, $message, $file, $line) {
    echo "🚨 Oops! Something happened!<br>";
    echo "Problem: $message<br>";
    echo "Location: $file on line $line<br>";
    return true; // I handled it!
}

Step 2: Tell PHP to Use It

<?php
set_error_handler("myErrorGuard");

Step 3: Now Errors Look YOUR Way

<?php
function myErrorGuard($level, $message, $file, $line) {
    echo "🚨 Oops! Something happened!<br>";
    echo "Problem: $message<br>";
    return true;
}

set_error_handler("myErrorGuard");

// This creates a warning
echo $undefined_variable;
// Output: 🚨 Oops! Something happened!
// Problem: Undefined variable $undefined_variable

Error Handler Parameters Explained

graph TD A["myErrorGuard Function"] --> B["$level - Error type number"] A --> C["$message - What went wrong"] A --> D["$file - Which file"] A --> E["$line - Which line"]
Parameter What It Tells You
$level The error type (like E_WARNING = 2)
$message Description of the problem
$file Which file has the error
$line Which line number

4️⃣ Global Exception Handler

The Ultimate Safety Net

Exceptions are like emergency situations. If nobody catches them, your app crashes!

A Global Exception Handler catches ALL uncaught exceptions. It’s like having a safety net under a tightrope walker.

Without Safety Net:

<?php
throw new Exception("Something broke!");
// CRASH! 💥 Ugly error message

With Safety Net:

<?php
function safetyNet($exception) {
    echo "😅 We caught a problem!<br>";
    echo "What happened: " . $exception->getMessage();
}

set_exception_handler("safetyNet");

throw new Exception("Something broke!");
// Output: 😅 We caught a problem!
// What happened: Something broke!

Real World Example

<?php
function globalExceptionHandler($e) {
    // Log the error secretly
    error_log("Exception: " . $e->getMessage());

    // Show friendly message to user
    echo "Oops! Something went wrong.";
    echo "Our team is fixing it!";
}

set_exception_handler("globalExceptionHandler");

// Now ANY uncaught exception gets handled nicely

When Does It Activate?

graph TD A["Exception Thrown"] --> B{Caught by try-catch?} B -->|Yes| C["Handled Locally"] B -->|No| D["Global Handler Catches It"] D --> E["Your Custom Response"]

5️⃣ Error vs Exception

The Big Difference

Think of it this way:

Error Exception
🏠 Analogy Fire alarm goes off You throw a ball
🎮 Control PHP triggers it YOU trigger it
🎣 Catching Custom handler try-catch block
💡 When Automatic On purpose

Errors: Things PHP Notices

<?php
// PHP notices this automatically
echo $undefined;  // Error: Notice

include "missing.php";  // Error: Warning

nonexistent();  // Error: Fatal

Exceptions: Things YOU Throw

<?php
// YOU decide to throw this
$age = -5;

if ($age < 0) {
    throw new Exception("Age can't be negative!");
}

Catching Exceptions (try-catch)

<?php
try {
    // Risky code goes here
    $result = 10 / 0;  // Uh oh!
    throw new Exception("Can't divide by zero!");
} catch (Exception $e) {
    // Handle the problem
    echo "Caught: " . $e->getMessage();
} finally {
    // Always runs, no matter what
    echo "Cleanup done!";
}

Visual Comparison

graph TD subgraph Errors A1["PHP Detects Problem"] --> A2["Error Handler"] A2 --> A3["Continue or Stop"] end subgraph Exceptions B1["You Throw Exception"] --> B2{try-catch?} B2 -->|Yes| B3["Caught &amp; Handled"] B2 -->|No| B4["Global Handler"] end

Converting Errors to Exceptions

You can turn errors INTO exceptions! This gives you one way to handle everything:

<?php
function errorToException($level, $msg, $file, $line) {
    throw new ErrorException($msg, 0, $level, $file, $line);
}

set_error_handler("errorToException");

try {
    echo $undefined;  // Error becomes exception!
} catch (ErrorException $e) {
    echo "Caught as exception: " . $e->getMessage();
}

🎯 Quick Summary

Concept Purpose Key Function
Error Types Different severity levels E_NOTICE, E_WARNING, E_ERROR
Error Reporting Choose what to show error_reporting()
Custom Handler Your own error handler set_error_handler()
Exception Handler Catch uncaught exceptions set_exception_handler()
try-catch Handle exceptions locally try { } catch { }

🌟 The Complete Picture

<?php
// 1. Report all errors
error_reporting(E_ALL);

// 2. Custom error handler
set_error_handler(function($level, $msg, $file, $line) {
    echo "Error caught: $msg";
    return true;
});

// 3. Global exception handler
set_exception_handler(function($e) {
    echo "Exception caught: " . $e->getMessage();
});

// Now your app is protected! 🛡️

💪 You Did It!

You’ve learned how PHP watches over your code like a guardian:

  1. Error Types - Different warning levels (notice → fatal)
  2. Error Reporting - Choosing what to see
  3. Custom Handlers - Taking control of errors
  4. Exception Handlers - The safety net
  5. Error vs Exception - Automatic vs thrown

Now go build something amazing, knowing your code has a safety net! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.