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(); $url = $request->url();
$method = $request->method(); $method = $request->method();
if (array_key_exists($url, self::$routes[$method])) { try {
$controller = self::$routes[$method][$url]['controller']; if (array_key_exists($url, self::$routes[$method])) {
$action = self::$routes[$method][$url]['action']; $controllerName = self::$routes[$method][$url]['controller'];
$actionName = self::$routes[$method][$url]['action'];
$controller = new $controller($request); // Check for controller existence
$response = $controller->$action(); if (!class_exists($controllerName)) {
throw new Exception(sprintf("Controller '%s' missing", $controllerName));
}
if ($response instanceof Render) { // Create controller object
$response->render(); $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 {
throw new Exception(sprintf("No route found for: %s", $url));
} }
} else { } catch (Exception $e) {
Exceptions::catchOne(new Exception("No route found for: $url")); Exceptions::catchOne($e);
} }
} }
} }