0

我对 codeigniter 中的错误处理有疑问。我的第一个问题是谁应该调用 show_error 方法?模型或控制器或视图?我打算把它放在这个特殊情况的模型中,因为模型是产生错误的地方,但是由于我的大部分业务逻辑都在控制器中,所以我决定在那里做。但是我想知道是否有“正确”的方法来做到这一点。

我的第二个问题是这个。在模型中,我添加了两个函数——一个返回数据,另一个返回错误消息。我的控制器在调用我的模型后测试错误情况,并尝试显示它。但它总是空的。

我的模型看起来像这样:

    public function errormessage()
    {
        return $this->_emess;
    }
    public someotherfunction()
    {
         if ( $switch_obj->connect() )
        {
            $retdata = $switch->showInterfaceAll(); 
            $switch->disconnect();  
            $this->_data = $retdata;
            return true;
        }
        else
        {
            print 'debug: assigning error message in model:';
            $this->_emess = $switch->errormessage();
            print $this->_emess;
            return false;
        }
          }

然后在我的控制器中,我有以下逻辑:

      if ($this->switches_model->someotherfunction($this->uri->segment(7) ) )
      {      
      $data['listofports'] = $this->switches_model->data;
      }
      else {
              print '<BR>in error path<BR>';
      show_error($this->switches_model->errormessage(), 123);
      }

从模型中的调试打印语句中,我知道已设置错误消息。但是当控制器尝试使用 show_error() 方法显示它时,我收到以下错误消息:

没有可用的状态文本。请检查您的状态码或提供您自己的消息文本。

为了证明这不是因为模型已经被销毁,我尝试在我的模型中添加一个析构函数并打印出调试行...

    public function __destruct()
    {
      print 'in the destructor';
    }

消息“在错误路径中”在“在析构函数中”之前打印,所以我假设模型仍然活着并且很好......

任何建议,将不胜感激。

谢谢。

更新 1

我发现了我的问题。如果您要通过一个合法的状态码,您需要通过一个合法的状态码。我认为您可以创建自定义状态编号,但它们必须是 HTTP 代码。但是,如果有人可以评论关于谁应该调用 show_error() 的问题 1,那将不胜感激。谢谢。

4

1 回答 1

1

The short answer to your first question is no, there is not a "correct" way to do it.

In your question, you said:

since most of my business logic is in the controller I decided to do it there.

This is up for debate and is probably not a debate that should be had on this site but I have found that generally, the controller is meant to be more of a dispatcher then anything else. So, your controller should be as small as possible. That being said, since the show_error() function is also deciding what view to display, I would call that a dispatching function and would put it in the controller. If you were not using that function but were using log_message() instead to store the error in a log and continue processing, then I would put that in the model because you can continue through the process after using that function. Again, this is personal choice and can be done either place but that is how I usually look at it.

于 2013-01-09T00:14:02.360 回答