如何从CodeIgniter库中抛出异常

时间:2012-08-28 19:26:34

标签: php codeigniter exception

我已经创建了一个依赖于某种特定方法的CodeIgniter库。这种方法过去是“隐藏的”(它没有记录,但似乎有效)。最终CodeIgniter将其设为protected,因此我无法从库中调用它。在GitHub的开发版CodeIgniter中,我可以使用一种新的公共方法。

在我的库中,我使用is_callable来检测要使用的方法,旧方法或新方法。问题是,在当前稳定版本的CodeIgniter中,既不存在。因此,库将失败。有没有一种方法可以优雅地错误输出,或者从我的构造函数中抛出异常?目前,如果两种方法都不可用,则脚本在尝试调用方法时将崩溃。

我不知道CodeIgniter库的约定是什么,因为缺少方法而无法正确加载。

编辑:以下是我要问的问题:

$this->func = is_callable(array($this->db, '_compile_select')) ? '_compile_select' : 'get_compiled_select';

如果这些都不存在(_compile_selectget_compiled_select),那么当图书馆试图调用$this->func时,它就会出错。我不知道惯例,我可以从库中调用show_error吗?从库的构造函数中抛出错误的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

如果目标只是一个漂亮的错误消息而不是致命的错误,那真的很简单:

$this->func = is_callable(array($this->db, '_compile_select')) ? '_compile_select' : 'get_compiled_select';

if ( ! is_callable(array($this, $this->func)))
{
    show_error("You can't use this library, you're missing a function");
}

基本上,只是不要假设get_compiled_select在条件检查中是可调用的。

  

我可以从库中调用show_error吗?

是的,这是core/Common.php中定义的功能之一,您可以在CI应用中的任何位置使用它。

当然,从技术上讲,这不是throw例外,但它是Codeigniter的惯例。如果您想要catch错误并尝试其他方法,则可能会出现问题:

try {
    $this->load->library('might_not_exist', 'alias');
} catch (Exception $e) {
    $this->load->library('definitely_exists', 'alias');
}

以上操作无效,因为show_error()将被加载程序调用并在执行catch块之前退出程序。

答案 1 :(得分:1)

我不确定但是看到这个网址我觉得这对你很有帮助。

http://codeigniter.com/forums/viewthread/67096/

另见

http://phpcodeignitor.blogspot.in/2011/07/php-exception.html

或试试这个

MY_Exceptions.php并将其放在/ applications / libraries /

 <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Exceptions extends CI_Exceptions{

    function MY_Exceptions(){
        parent::CI_Exceptions();

    }

    function show_404($page = '')
    {
    echo 'test';
    }

    function show_error($heading, $message, $template = 'error_general')
    {
echo 'test';    
}

    function show_php_error($severity, $message, $filepath, $line)
    {
         echo 'test';
         }
}
?>
MY_Exceptions中的

函数似乎根本没有被覆盖。 “例外”中的函数是运行的函数