CodeIgniter:Try-Catch在模型类中不起作用


CodeIgniter: Try Catch is not working in model class

我对列有一个unique约束。当这段代码运行时,我会从框架中得到错误日志,但这并不是我在Exception块中给出的
如果存在唯一列,那么我想查询它的主键并将其设置为$id,然后返回页面。现在它在数据库错误时停止,不进入Catch block
这是我的代码:

try {
            $result = $this->db->insert('email', $new_email);
            if ($result)
            {
                $id = $this->db->insert_id();    
            } else {
                throw new Exception("$$$$$$$$$$$$$Log database error");
            }
        } catch (Exception $e) {
            log_message('error',$e->getMessage());
            return;
        }

**Error Messages**我从框架中得到:

DEBUG - 2013-04-07 05:00:38 --> DB Transaction Failure
ERROR - 2013-04-07 05:00:38 --> Query error: Duplicate entry 

我不知道它怎么了。

CI对异常没有很好的支持。DB查询将调用一些模糊的CI error_logging,称为show_error((。您需要做的是设置正确的异常处理。

基本上,你可以遵循整个食谱。

现在,所有数据库错误都将自动引发异常。另外,您在整个CI应用程序中都有良好的异常处理能力。

注册一个将PHP错误转换为异常的自定义错误处理程序,例如将其放在config/config.PHP 的顶部

function my_error_handler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno))
    {
        // This error code is not included in error_reporting
        return;
    }
    log_message('error', "$errstr @$errfile::$errline($errno)" );
    throw new ErrorException( $errstr, $errno, 0, $errfile, $errline );
}
set_error_handler("my_error_handler");

注册一个未捕获的异常处理程序,在config/config.php 中放入类似的内容

function my_exception_handler($exception)
{
    echo '<pre>';
    print_r($exception);
    echo '</pre>';
    header( "HTTP/1.0 500 Internal Server Error" );
}
set_exception_handler("my_exception_handler");

设置终止处理程序:

function my_fatal_handler()
{
    $errfile = "unknown file";
    $errstr  = "Fatal error";
    $errno   = E_CORE_ERROR;
    $errline = 0;
    $error = error_get_last();
    if ( $error !== NULL )
    {
        echo '<pre>';
        print_r($error);
        echo '</pre>';
        header( "HTTP/1.0 500 Internal Server Error" );
    }
}
register_shutdown_function("my_fatal_handler");

设置一个将断言转换为异常的自定义断言处理程序,在config/config.php中放入类似的内容:

function my_assert_handler($file, $line, $code)
{
    log_message('debug', "assertion failed @$file::$line($code)" );
    throw new Exception( "assertion failed @$file::$line($code)" );
}
assert_options(ASSERT_ACTIVE,     1);
assert_options(ASSERT_WARNING,    0);
assert_options(ASSERT_BAIL,       0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

在你的控制器中使用这样的包装器

public function controller_method( )
{
    try
    {
        // normal flow
    }
    catch( Exception $e )
    {
        log_message( 'error', $e->getMessage( ) . ' in ' . $e->getFile() . ':' . $e->getLine() );
        // on error
    }
}

你可以根据自己的喜好调整和定制整件事!

希望这能有所帮助。

您还需要截取CI show_error方法。将其放入application/core/MY_exceptions.hp:

class MY_Exceptions extends CI_Exceptions
{
    function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        log_message( 'debug', print_r( $message, TRUE ) );
        throw new Exception(is_array($message) ? $message[1] : $message, $status_code );
    }
}

并在application/config/database.php中保留此设置为FALSE,以将数据库错误转换为异常。

$db['default']['db_debug'] = TRUE;

CI有一些(非常(弱点,比如异常处理,但这将在很大程度上纠正这一点。

如果要使用事务,请确保对异常进行回滚。与此相关的NEVER(与EVER中一样(使用持久连接作为打开事务,其他会话特定的DB状态将由其他会话获取/继续。

如果启用数据库调试,则数据库中的错误将被路由到Exceptions核心类,然后调用exit(),这意味着脚本甚至永远不会到达您的if条件。

打开application/config/database.php并尝试将db_debug设置为false。无论如何,对于生产网站来说,这是一个好主意,因为您不希望任何SQL查询问题发布有关数据库结构的信息。

此外,不相关的,要小心在双引号中使用$,因为它会被解析为一个变量(甚至是一行中的一堆——它实际上是一个变量变量变量…(

如果将结果设置在try块之外会怎样?或者三元运算符:

$result = $this->db->insert('email', $new_email);
try {
  $result = ($result) ? $result || false;  
  if ($result) {
    $id = $this->db->insert_id();    
  } else {
    throw new Exception("$$$$$$$$$$$$$Log database error");
  }
} catch (Exception $e) {
  log_message('error',$e->getMessage());
  return;
}

正如@jcorry所说,如果不知道$result的真正价值,很难知道。

$db['default']['db_debug'] = FALSE;

https://forum.codeigniter.com/archive/index.php?thread-8484.html

如果您查看CodeIgniter的代码,您会发现它在bot system/core和ci_system/core文件夹中的CodeIgniter.php中设置了自己的错误处理。

/*
 * ------------------------------------------------------
 *  Define a custom error handler so we can log PHP errors
 * ------------------------------------------------------
 */
    set_error_handler('_error_handler');
    set_exception_handler('_exception_handler');
    register_shutdown_function('_shutdown_handler');

前两个函数处理错误处理。为了得到你的尝试。。捕捉块工作,你只需要关闭这个。

使用restore_error_handler和restore_exception_handler函数,我们可以将这些错误处理函数重置回默认值。

    restore_error_handler();
    restore_exception_handler();

或者。。。如果您希望保留错误处理程序以便稍后恢复它们。

    //Disable CodeIgniter error handling so we can use try catch blocks
    $errorHandlers = array();
    do {
        $errorHandler = set_error_handler(function() {}); //Get the current handler
        array_push($errorHandlers, $errorHandler); //Store the handler so that it can be restored if necessary
        for ($i = 0; $i < 2; $i++) { //We have to reset twice to get to the previous handler since we added a dummy handler
            restore_error_handler();
        }
    }
    while (!is_null($errorHandler)); //Is null when there are no handlers
    $exceptionHandlers = array(); //Do the same with exceptions
    do {
        $exceptionHandler = set_exception_handler(function() {});
        array_push($exceptionHandlers, $exceptionHandler);
        for ($i = 0; $i < 2; $i++) {
            restore_exception_handler();
        }
    }
    while (!is_null($exceptionHandler));
    try {
        //Your code goes here
    }
    catch (Error $e) {
        //Handle error
    }
    catch (Exception $e) {
        //Handle exception
    }
    //Restore all error handlers
    foreach ($errorHandlers as $errorHandler) {
        if (isset($errorHandler)) {
            set_error_handler($errorHandler);
        }
    }
    foreach ($exceptionHandlers as $exceptionHandler) {
        if (isset($exceptionHandler)) {
            set_exception_handler($exceptionHandler);
        }
    }

我们可以禁用所有自定义错误处理程序,并根据需要存储它们以进行恢复。

我在保存和恢复时使用循环,以防设置了其他错误处理程序。通过这种方式,您可以恢复所有的错误处理程序,因为其他地方可能存在类似的代码,这些代码会出于某种特定目的返回到上一个错误处理程序并将被保留。