Update router. Better error handling

This commit is contained in:
Maarten 2024-11-25 19:49:29 +01:00
parent 75a22b7b52
commit afa8a341bd

View file

@ -75,18 +75,36 @@ class Router
$url = $request->url();
$method = $request->method();
try {
if (array_key_exists($url, self::$routes[$method])) {
$controller = self::$routes[$method][$url]['controller'];
$action = self::$routes[$method][$url]['action'];
$controllerName = self::$routes[$method][$url]['controller'];
$actionName = self::$routes[$method][$url]['action'];
$controller = new $controller($request);
$response = $controller->$action();
// Check for controller existence
if (!class_exists($controllerName)) {
throw new Exception(sprintf("Controller '%s' missing", $controllerName));
}
// Create controller object
$controller = new $controllerName($request);
// Check for method on controller
if (!method_exists($controller, $actionName)) {
throw new Exception(sprintf("Method '%s' not found on '%s'", $actionName, $controllerName));
}
// Build response object of action
$response = $controller->$actionName();
// Render action
if ($response instanceof Render) {
$response->render();
}
} else {
Exceptions::catchOne(new Exception("No route found for: $url"));
throw new Exception(sprintf("No route found for: %s", $url));
}
} catch (Exception $e) {
Exceptions::catchOne($e);
}
}
}