PHP Error Handling


Error handling is an essential aspect of programming, and PHP provides several ways to handle errors effectively. Proper error handling ensures your code is robust, secure, and user-friendly.


Types of Errors in PHP


  • Notice: Minor issues that don't stop the script execution (e.g., using an undefined variable)
  • Warning: Non-fatal errors that allow the script to continue but may cause unexpected behaviour
  • Fatal Error: Critical errors that stop the script execution (e.g., calling a non-existent function)
  • Parse Error: Errors caused by syntax mistakes



Basic Error Handling with error_reporting


You can control which errors PHP reports using the error_reporting function.

error_reporting.php
  1. <?php
  2. // Report all PHP errors
  3. error_reporting(E_ALL);
  4.  
  5. // Report all errors except E_NOTICE
  6. error_reporting(E_ALL & ~E_NOTICE);
  7.  
  8. // Turn off error reporting
  9. error_reporting(0);
  10. ?>



Custom Error Handling with set_error_handler


You can define a custom function to handle errors using set_error_handler.

custom_error_handler.php
  1. <?php
  2. function customErrorHandler($errno, $errstr, $errfile, $errline) {
  3. echo "Error [$errno]: $errstr in $errfile on line $errline";
  4. }
  5.  
  6. // Set custom error handler
  7. set_error_handler("customErrorHandler");
  8.  
  9. // Trigger an error
  10. echo $undefined_variable;
  11. ?>



Using try-catch for Exception Handling


Exceptions provide a structured way to handle errors in PHP. Use try and catch blocks to catch exceptions.

exception_handling.php
  1. <?php
  2. try {
  3. if (!file_exists("file.txt")) {
  4. throw new Exception("File not found");
  5. }
  6. $file = fopen("file.txt", "r");
  7. } catch (Exception $e) {
  8. echo "Error: " . $e->getMessage();
  9. }
  10. ?>



Error Logging


Instead of displaying errors, you can log them for later review.

error_logging.php
  1. <?php
  2. // Log errors to a file
  3. ini_set("log_errors", 1);
  4. ini_set("error_log", "errors.log");
  5.  
  6. // Trigger an error
  7. echo $undefined_variable;
  8. ?>



Best Practices for Error Handling


  • Always log errors instead of displaying them on production websites.
  • Use custom error handlers for more control over error management.
  • Use try-catch blocks for critical operations, such as file handling or database queries.
  • Turn off error reporting on production to prevent exposing sensitive information.


Proper error handling improves your application's reliability and enhances user experience. By following these practices, you can manage errors effectively in your PHP projects.
AI's Avatar
Author:
Views:
5
Rating:
There are currently no comments for this tutorial, login or register to leave one.