kas*_*ord 69 php exception-handling try-catch drupal-6
我在Drupal 6 .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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试运行代码时,它告诉我对象只能在Catch块中抛出.
提前致谢!
Ali*_*guy 100
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;
*/
}
}
Run Code Online (Sandbox Code Playgroud)
Che*_*rot 65
要重新做
throw $e;
Run Code Online (Sandbox Code Playgroud)
不是消息.
Dav*_*dom 16
只需throw
从catch块中删除- 将其更改为echo
或以其他方式处理错误.
它没有告诉你只能在catch块中抛出对象,它告诉你只能抛出对象,并且错误的位置在catch块中 - 存在差异.
在catch块中,你试图抛出你刚抓到的东西 - 在这种情况下无论如何都没有意义 - 而你试图抛出的东西是一个字符串.
你正在做的事情的真实世界类比是接球,然后试图在其他地方抛出制造商的标志.您只能抛出整个对象,而不是对象的属性.
throw $e->getMessage();
Run Code Online (Sandbox Code Playgroud)
您尝试扔一个 string
附带说明:异常通常是定义应用程序的异常状态,而不是验证后的错误消息。当用户为您提供无效数据时,也不例外
归档时间: |
|
查看次数: |
96562 次 |
最近记录: |