Understanding PHP Error Types

PHP classifies errors into several types, each with a different severity level. These include notices, warnings, and fatal errors. Notices are for non-critical issues (e.g., undefined variables), warnings indicate problems that don’t stop execution (e.g., invalid function arguments), and fatal errors halt script execution.

Error LevelDescriptionStoppable?
E_NOTICEIndicates a possible error conditionNo
E_WARNINGSerious runtime warningNo
E_ERRORFatal runtime errorYes
E_PARSECompile-time parse errorYes
E_RECOVERABLE_ERRORCatchable fatal errorYes
E_USER_NOTICEUser-generated noticeNo
E_USER_WARNINGUser-generated warningNo
E_USER_ERRORUser-generated errorYes

Custom Error Handling with set_error_handler()

PHP allows you to define custom error handlers using set_error_handler(). This is particularly useful for logging errors or displaying user-friendly messages.

<?php
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    $errorLog = "error_" . date("Y-m-d") . ".log";
    $message = "[$errno] $errstr in $errfile on line $errline\n";
    file_put_contents($errorLog, $message, FILE_APPEND);
    return true;
}

set_error_handler("customErrorHandler");

// Trigger a notice
echo $undefinedVariable;
?>

This script logs any notice-level error to a daily log file instead of displaying it directly to the user.

Exception Handling with try...catch...finally

Exceptions in PHP are handled using try, catch, and finally blocks. This is the preferred way to handle runtime exceptions that may occur in object-oriented code.

<?php
class Database {
    public function connect($host, $user, $pass) {
        if (empty($host) || empty($user)) {
            throw new InvalidArgumentException("Host and user must not be empty.");
        }
        return "Connected to $host as $user";
    }
}

try {
    $db = new Database();
    $result = $db->connect("", "admin", "password");
    echo $result;
} catch (InvalidArgumentException $e) {
    echo "Invalid input: " . $e->getMessage();
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
} finally {
    echo "\nConnection attempt completed.";
}
?>

In this example, the connect() method throws an exception if required parameters are missing. The try...catch block ensures that the application can gracefully handle the exception.

Custom Exceptions

Creating custom exception classes allows for more specific error handling. PHP allows you to extend the built-in Exception class to define your own exceptions.

<?php
class ValidationException extends Exception {}

function validateEmail($email) {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new ValidationException("Invalid email address format.");
    }
    return true;
}

try {
    validateEmail("invalid-email");
} catch (ValidationException $e) {
    echo "Validation failed: " . $e->getMessage();
}
?>

This example defines a ValidationException class and uses it to handle invalid email inputs.

Debugging with var_dump() and print_r()

For quick debugging, PHP provides var_dump() and print_r() to inspect variable contents. var_dump() shows variable type and value, while print_r() is more suitable for arrays and objects.

<?php
$data = [
    "name" => "Alice",
    "age" => 30,
    "roles" => ["user", "admin"]
];

var_dump($data);
echo "\n";
print_r($data);
?>

Use these functions during development to inspect the state of your data structures.

Debugging with error_log()

In production environments, avoid using var_dump() or print_r() for debugging. Instead, use error_log() to log messages to the server error log or a custom file.

<?php
function processInput($input) {
    error_log("Received input: " . print_r($input, true));
    // processing logic
}
?>

This is a cleaner and more secure way to debug without exposing internal data to users.

Final Notes on Best Practices

  • Always use try...catch blocks for exception handling.
  • Define custom exceptions for better clarity and control.
  • Use set_error_handler() to log non-fatal errors.
  • Avoid displaying raw errors to end users in production.
  • Use debugging tools like var_dump() and print_r() only in development.
  • Use error_log() for debugging in production environments.

Learn more with useful resources