【发布时间】:2016-09-21 20:37:06
【问题描述】:
我正在更新我不久前完成的框架。我从社区得到了一些反馈,并决定构建一个小型的可移植 MVC 框架来存放我的包。
我目前正在开发路由器,当我向框架提供它应该获取的 URL 时,它运行良好。我使用throw new Exception("MyMessage") 使验证URL 更加面向对象并且更简单。
但是,这是我第一次尝试这样做,而且我的 catch 块似乎没有捕获错误。
具体来说,每当try 块中出现错误时,我希望它触发我在catch 块中的一些代码。
这是完整的try/catch 块...
try
{
if (isset($url[0]) && isset($url[1]) && isset($url[2]) && $url[0] . $url[1] . $url[2] != "")
{
//Figure out if we're handling a package, or working in the package manager.
if ($url[0] != "ignition" && $url[0] != "")
{
if (!file_exists("../packages/" . $url[0]))
{
throw new Exception($manager_error = "Package \"" . $url[0] . "\" not found.");
}
else
{
$this->package = $url[0];
$this->path = "../packages/$this->package/controllers/";
}
unset($url[0]);
}
elseif ($url[0] == "")
throw new Exception("No package name provided.");
//Check if controller exists.
if ($url[1] != "")
{
//Check if controller file exists.
if (file_exists($this->path . $url[1] . ".php"))
{
$this->controller = $url[1];
require_once($this->path . "$this->controller.php");
unset($url[1]);
//Check that controller exists in file.
if (class_exists($this->controller))
{
$this->controller = new $this->controller;
//Check that method exists in controller.
if ($url[2] != "")
{
if (method_exists($this->controller, $url[2]))
{
$this->method = $url[2];
unset($url[2]);
if (!empty($url))
$this->params = array_values($url);
}
else
throw new Exception("Method \"" . $url[2] . "\" not found in controller \"" . get_class($this->controller) . "\".");
}
else
throw new Exception("No method name provided.");
}
else
throw new Exception("Controller \"$this->controller\" not contained in it's file.");
} else {
throw new Exception("Controller file \"" . $url[1] . ".php\" not found.");
}
}
else
throw new Exception("No controller name provided.");
}
else
{
//Check if we have one or more arguments, but less than the three
//we need for a complete route.
if (!isset($url[0]))
$url[0] = "";
if (!isset($url[1]))
$url[1] = "";
if (!isset($url[2]))
$url[2] = "";
if ($url[0] . $url[1] . $url[2] != "") {
if ($url[0] == "")
throw new Exception("No package name provided.");
elseif ($url[1] == "")
throw new Exception("No controller name provided.");
elseif ($url[2] = "")
throw new Exception("No method name provided.");
}
}
}
catch (Exception $e)
{
unset($url);
$this->manager_error = $e->getMessage();
$this->package = "ignition";
$this->controller = "ignition";
$this->method = "notFound";
$this->path = "../package_manager/controllers/";
$this->params[] = $this->manager_error;
require_once($this->path . "$this->controller.php");
$this->controller = new $this->controller;
}
我尝试制作一个非常简单的版本,我只是回显了一些文本并在地址栏中输入了一些错误的 URL,以尝试从 catch 块中获取一些东西,但我没有成功。
我还想提一下,这是在类的构造函数中,如果这有什么不同的话。
我在这里做错了什么,如何更改此脚本以捕获异常?
【问题讨论】:
-
如果没有看到抛出异常的代码,很难回答这个问题。
-
如果你愿意,我可以发布整个脚本。只要条件抛出异常,它在哪里抛出有关系吗?
-
至少向我们展示完整的
try/catch代码(这是您需要我们帮助的)。 -
只是为了涵盖所有基础,这里是否涉及命名空间?
-
这就是
__construct!?
标签: php validation exception exception-handling php-7