Error handling ni muhimu ili kutambua na kurekebisha matatizo kwenye code.
Hata hivyo, ku-display error messages kamili kwa users kunaweza:

Kufichua database structure

Kufichua paths za files

Kutoa hints kwa attackers

Goal: Log errors internally na display friendly messages kwa users.

โš™๏ธ 2. PHP Error Reporting Setup
<?php
// Development environment
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Production environment (safe)
ini_set('display_errors', 0); // do not show errors to users
ini_set('log_errors', 1); // log errors instead
ini_set('error_log', __DIR__ . '/errors.log'); // error log file
?>


๐Ÿ’ก Maelezo:

In development: show errors for debugging.

In production: hide errors, log them for developers.

๐Ÿงฉ 3. Custom Error Handling
<?php
// Custom error handler
function customError($errno, $errstr, $errfile, $errline){
// Log detailed error internally
error_log("Error [$errno] in $errfile on line $errline: $errstr");

// Show friendly message to user
echo "โŒ Something went wrong. Please try again later.";
}

// Set custom error handler
set_error_handler("customError");

// Example: undefined variable
echo $undefinedVar;
?>


Output to user:

โŒ Something went wrong. Please try again later.


Internal log (errors.log):

Error [8] in /var/www/html/index.php on line 15: Undefined variable $undefinedVar

๐Ÿ”‘ 4. Best Practices

Never display detailed errors to users โ€“ always use friendly messages.

Log all errors โ€“ internal error logs help debugging.

Use try-catch for exceptions โ€“ handle runtime errors gracefully.

Separate development and production settings โ€“ dev shows errors, prod hides them.

Regularly monitor logs โ€“ fix recurring issues promptly.

โœ… 5. Hitimisho

Proper error handling improves application stability na security.

Friendly messages + internal logging = safe & maintainable code.

Combine with input validation, prepared statements, na session security kwa maximum protection.

๐Ÿ”— Tembelea:

๐Ÿ‘‰ https://www.faulink.com/

Kwa mafunzo zaidi ya PHP, secure error handling, na best practices za web applications.