PHP和Codeigniter中的错误处理.怎么做?避免递归代码


Error handling in PHP and Codeigniter. How to do it? Avoiding recursive code

我正在使用Codeigniter。

我开发了各种功能,如果按预期使用,它们会完美工作。

一个这样的脚本,whois脚本检查域名的所有者。然而,如果用户键入了一个无效的域名,那么到处都会出现各种错误。

例如,如果用户在堆栈中键入-com,这当然不是一个有效的域。因此,当我调用执行查询的助手时,不会返回任何结果,并且会返回各种错误。当我试图向用户显示一个空数组时,也会出现错误。

我的问题与错误有关。

我可以使用preg_match并检查域是否有效。如果没有,我设置一个错误变量,我打算输出给用户。

然而,在我的控制器进入if-else语句(该语句决定是显示错误页面还是显示结果页面)之前,程序正在运行查询,并且访问方法以获取没有错误的数据将获得要传递到结果视图的数据。

我知道有一个错误,但仍然显示了许多其他错误,因为一个无效的项目被传递给了我的其他脚本。

有了Codeigniter和MVC设置,在不必使用重复执行相同操作的异常的情况下,捕捉错误并将其显示给用户的最佳方式是什么?

感谢

用创意编辑

try
{
$this->load->model('whois');
$this->whois->process('domain.-com');
}
catch
{
$this->load->view('errors',$errordata);
$this->load->view('footer');
die;
}
$this->load->view('normal_content');
$this->load->view('footer');

这是使用代码点火器异常的建议设置吗?在我的模型中,如果出现问题,函数将抛出异常。catch语句将显示它们并终止,从而不显示内容。。这似乎不对。。?

以下是我通常处理此问题的方法:

  1. 将您的表格寄回同一路线
  2. 如果有错误,请再次显示带有错误状态的表单
  3. 如果一切顺利,请立即重定向到下一步/成功状态

样本代码:

<?php
...
public function form()
{
    if (strtoupper($this->input->server('REQUEST_METHOD')) == 'POST')
    {
        try {
            // handle all your validation here
            redirect('success_route');
            exit;
        }
        catch (Exception $e)
        {
            // this could get a little fancier, but a simple solution is to pass the exception
            // directly to the view.  you could also load the `errors` view here, but return the
            // content to a variable and pass to your full view
            $this->load->vars('exception', $e);
        }
    }
    $this->load->view('normal_content');
    $this->load->view('footer');
}
...

您必须执行以下

1) database.php:$db[default']['db_debug']=FALSE;

2) 在您的模式文件中

try {
   $query_str = "SELECT * FROM `pro_property` WHERE username = '".$username."'";
   $result = $this->db->query($query_str);
   if (!$result)
   {
       throw new Exception('error in query');
       return false;
   }        
   return $result;
} catch (Exception $e) {
    print_r($e);
}