Katika mfumo wa MVC (Model-View-Controller), error handling ni muhimu kwa:

Kudhibiti makosa ya mfumo bila kuvunja application.

Kuwapa watumiaji ujumbe rafiki badala ya technical errors.

Kurahisisha debugging na logging kwa developer.

PHP inaruhusu exceptions, custom error pages, na error logging β€” vyote vinaweza kutumika vizuri ndani ya MVC structure.

πŸ‘‰ Soma zaidi kuhusu PHP MVC kwenye Faulink Learning Center
.

βš™οΈ 2. Aina za Makosa (Types of Errors)
Aina ya Kosa Maelezo
Notice / Warning Makosa madogo yasiyosimamisha script
Fatal Error Kosa kubwa linalosimamisha script
Exception Makosa yanayoweza kudhibitiwa kwa try...catch
Custom Error Makosa maalum ya developer (mfano 404, 500)
🧩 3. Muundo wa Project
mvc_project/
β”‚
β”œβ”€β”€ app/
β”‚ β”œβ”€β”€ controllers/
β”‚ β”œβ”€β”€ models/
β”‚ β”œβ”€β”€ views/
β”‚ β”‚ β”œβ”€β”€ errors/
β”‚ β”‚ β”‚ β”œβ”€β”€ 404.php
β”‚ β”‚ β”‚ └── 500.php
β”‚ β”‚ └── home.php
β”œβ”€β”€ core/
β”‚ β”œβ”€β”€ Router.php
β”‚ β”œβ”€β”€ Controller.php
β”‚ └── ErrorHandler.php
└── public/
└── index.php

βš™οΈ 4. ErrorHandler Class (core/ErrorHandler.php)
<?php
class ErrorHandler {
public static function register(){
set_error_handler([self::class, 'handleError']);
set_exception_handler([self::class, 'handleException']);
}

public static function handleError($errno, $errstr, $errfile, $errline){
error_log("Error [$errno]: $errstr in $errfile on line $errline");
self::displayErrorPage(500, "A system error occurred. Please try again later.");
}

public static function handleException($exception){
error_log("Uncaught Exception: " . $exception->getMessage());
self::displayErrorPage(500, "Unexpected error. Contact admin if it persists.");
}

private static function displayErrorPage($code, $message){
http_response_code($code);
include "../app/views/errors/{$code}.php";
exit;
}
}


πŸ“Œ Kazi ya ErrorHandler:

Inasajili error na exception handlers.

Inarekodi maelezo kwenye log.

Inaonyesha page maalum ya error (mfano 404, 500).

🧩 5. Example Error Pages
app/views/errors/404.php
<!DOCTYPE html>
<html>
<head><title>404 - Page Not Found</title></head>
<body>
<h2>404 - Ukurasa Haujapatikana</h2>
<p>Samahani, ukurasa uliouomba haupo.</p>
<a href="https://www.faulink.com/&quot;&gt;➑️ Rudi Faulink.com</a>
</body>
</html>

app/views/errors/500.php
<!DOCTYPE html>
<html>
<head><title>500 - Internal Server Error</title></head>
<body>
<h2>500 - Tatizo la Ndani ya Server</h2>
<p>Kuna kosa limetokea. Tafadhali jaribu tena baadae.</p>
<a href="https://www.faulink.com/&quot;&gt;➑️ Rudi Kwenye Msingi (Faulink.com)</a>
</body>
</html>

🧩 6. Front Controller (public/index.php)
<?php
require_once '../core/ErrorHandler.php';
require_once '../core/Router.php';

ErrorHandler::register(); // Enable global error handling

$router = new Router();

// Example routes
$router->add('GET', '/', function(){
echo "Welcome to MVC Project! Visit <a href='https://www.faulink.com/&apos;&gt;Faulink.com&lt;/a&gt;&quot;;
});

$router->add('GET', '/test', function(){
// Example: force an exception
throw new Exception("Something went wrong!");
});

$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$router->dispatch($method, $uri);


πŸ“Œ Kila kosa au exception litashughulikiwa na ErrorHandler.

🧩 7. Router Error Handling (core/Router.php)
<?php
class Router {
private $routes = [];

public function add($method, $uri, $callback){
$this->routes[] = compact('method', 'uri', 'callback');
}

public function dispatch($method, $uri){
foreach($this->routes as $route){
if($method === $route['method'] && preg_match("#^".$route['uri']."$#", $uri, $matches)){
array_shift($matches);
return call_user_func_array($route['callback'], $matches);
}
}
http_response_code(404);
include "../app/views/errors/404.php";
exit;
}
}


πŸ“Œ Router inaonyesha ukurasa wa 404 ikiwa route haipo.

🧰 8. Logging Errors

Kwa logging ya makosa:

ini_set('log_errors', 1);
ini_set('error_log', __DIR__.'/../logs/error.log');
error_reporting(E_ALL);


βœ… Hii itahifadhi maelezo ya makosa ndani ya logs/error.log.
πŸ“ Hakikisha umeunda folder logs/.

πŸ”‘ 9. Best Practices

βš™οΈ Usionyeshe makosa ya ndani kwa user (Production mode).

🧱 Tumia custom error pages (404, 500).

🧩 Tumia try...catch kwa database na API calls.

πŸͺ΅ Log all errors kwa debugging.

🧭 Weka error handler moja kuu (ErrorHandler.php).

βœ… 10. Hitimisho

Error handling kwenye MVC ni msingi wa:

Usalama

Utulivu wa mfumo

UX bora kwa watumiaji

Kwa kutumia ErrorHandler class, custom error pages, na logging, utakuwa na mfumo salama na unaotegemewa.

πŸ”— Linki Muhimu:

🌐 Tovuti Kuu: https://www.faulink.com