我在Drupal6的.module文件中有一个PHP函数。我正在尝试在执行更密集的任务(如数据库查询)之前运行初始变量验证。在C#中,我过去常常在Try代码块的开头实现IF语句,如果验证失败,就会抛出新的异常。抛出的异常将在Catch块中捕获。以下是我的PHP代码:
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
throw $e->getMessage();
}
}
但是,当我尝试运行代码时,它告诉我只能在Catch块中抛出对象。
提前感谢!
发布于 2012-01-28 07:04:42
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
发布于 2012-01-28 07:06:03
重新抛出do
throw $e;
而不是信息。
发布于 2012-01-28 07:02:59
你试图抛出一个string
throw $e->getMessage();
您只能抛出实现\Throwable
的对象,例如\Exception
。
作为附注:异常通常是为了定义应用程序的异常状态,而不是为了验证后的错误消息。当用户给你提供无效数据时,这不是一个例外
https://stackoverflow.com/questions/9041173
复制相似问题