2017-06-22 61 views
0

我想處理MySQL查詢中的錯誤作爲例外。如何使用異常查詢?

例如,如果我正在插入一條記錄,但一列不在表中,那麼它會向我顯示一個錯誤。 有沒有辦法處理它,以便用戶無法看到錯誤?

回答

1

配置項對異常沒有很好的支持。您需要做的是設置適當的異常處理。

現在你所有的數據庫錯誤都會自動拋出異常。作爲獎勵,您在整個CI應用程序中都有良好的異常處理。

註冊該轉換PHP錯誤到異常的自定義的ErrorHandler,比如把這個在你的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;