JINSI YA KUTENGENEZA ERROR HANDLING KWA MVC PROJECTS (MVC ERROR HANDLING)
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/">➡️ 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/">➡️ 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/'>Faulink.com</a>";
});
$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
🚀 Unahitaji mfumo au website ya biashara?
Chagua huduma hapa chini kisha mteja bofya moja kwa moja kwenda kwenye ukurasa wa huduma au kuwasiliana nasi kwa WhatsApp.