如何使用查询异常?

时间:2017-06-22 09:20:38

标签: php codeigniter codeigniter-3

我想将MySQL查询中的错误视为异常。

例如,如果我正在插入记录但是列不在表中,那么它将显示错误。 有没有办法处理它,以便用户无法看到错误?

1 个答案:

答案 0 :(得分:1)

CI对异常没有很好的支持。您需要做的是设置适当的异常处理。

现在所有数据库错误都会自动抛出异常。作为奖励,您可以在整个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 );
    }
}

并在application/config/database.php上设置FALSE此设置,以便将数据库错误转换为例外。

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