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有一些(非常)弱点,例如异常处理,但是要纠正这一点还有很长的路要走。
如果要使用事务,请确保对异常进行回滚。与此相关(从不像以往一样),请使用持久性连接,因为打开的事务和其他特定于会话的数据库状态将被其他会话获取/继续。