您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

CI对异常没有很好的支持。您的数据库查询调用一些模糊的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.PHP中:

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 );
    }
}

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

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

CI有一些(非常)弱点,例如异常处理,但是要纠正这一点还有很长的路要走。

如果要使用事务,请确保对异常进行回滚。与此相关(从不像以往一样),请使用持久性连接,因为打开的事务和其他特定于会话的数据库状态将被其他会话获取/继续。

其他 2022/1/1 18:20:30 有512人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶