CodeIgniter -如何捕获数据库错误?

时间:2022-10-28 10:56:54

Is there a way to make CI throw an exception when it encounters a DB error instead of displaying a message like:

当CI遇到DB错误时,是否有办法让它抛出异常,而不是显示如下消息:

A Database Error Occurred Error Number: 1054 Unknown column 'foo' in 'where clause' SELECT * FROM (FooBar) WHERE foo = '1'

数据库出错:在where子句' SELECT * FROM (FooBar)中出现1054未知列'foo',其中foo = '1'

NOTE: I only want this to happen in one controller. In the other controllers, I'm happy for it to display the DB error messages.

注意:我只希望在一个控制器中发生这种情况。在其他控制器中,我很高兴它显示DB错误消息。

9 个解决方案

#1


51  

Try these CI functions

试试这些词功能

$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)

#2


29  

Maybe this:

也许是这样的:

$db_debug = $this->db->db_debug; //save setting

$this->db->db_debug = FALSE; //disable debugging for queries

$result = $this->db->query($sql); //run query

//check for errors, etc

$this->db->db_debug = $db_debug; //restore setting

#3


22  

In Codeigniter 3.0 (CI3), all you have to do is $this->db->error()

在Codeigniter 3.0 (CI3)中,您所需要做的就是$this->db->error()

If you need to get the last error that has occured, the error() method will return an array containing its code and message

如果需要获取已发生的最后一个错误,error()方法将返回一个包含其代码和消息的数组

http://www.codeigniter.com/user_guide/database/queries.html#handling-errors

http://www.codeigniter.com/user_guide/database/queries.html处理错误

#4


14  

You must turn debug off for database in config/database.php ->

必须在配置/数据库中关闭数据库的调试。php - >

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

It is better for your website security.

这对你的网站安全更好。

#5


10  

I know this thread is old, but just in case there's someone else having this issue. This is a trick I used without touching the CI db classes. Leave your debug on and in your error view file, throw an exception.

我知道这条线是旧的,但是以防有人有这个问题。这是我在不接触CI db类的情况下使用的技巧。将调试留在错误视图文件中,抛出一个异常。

So in you db config, you have :

在你的db配置中,你有

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

Then in your db error view file, mine is in application/errors/error_db.php replace all content with the following:

然后在您的db错误视图文件中,我的是应用程序/错误/error_db。php将所有内容替换为以下内容:

<?php
$message = preg_replace('/(<\/?p>)+/', ' ', $message);
throw new Exception("Database error occured with message : {$message}");

?>

Since the view file will be called, the error will always get thrown as an exception, you may later add different views for different environment.

由于视图文件将被调用,错误将被作为一个异常抛出,您可以稍后为不同的环境添加不同的视图。

#6


4  

I have created an simple library for that:

我为此创建了一个简单的库:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class exceptions {

    public function checkForError() {
        get_instance()->load->database();
        $error = get_instance()->db->error();
        if ($error['code'])
            throw new MySQLException($error);
    }
}

abstract class UserException extends Exception {
    public abstract function getUserMessage();
}

class MySQLException extends UserException {
    private $errorNumber;
    private $errorMessage;

    public function __construct(array $error) {
        $this->errorNumber = "Error Code(" . $error['code'] . ")";
        $this->errorMessage = $error['message'];
    }

    public function getUserMessage() {
        return array(
            "error" => array (
                "code" => $this->errorNumber,
                "message" => $this->errorMessage
            )
        );
    }

}

The example query:

这个示例查询:

function insertId($id){
    $data = array(
        'id' => $id,
    );

    $this->db->insert('test', $data);
    $this->exceptions->checkForError();
    return $this->db->insert_id();
}

And I can catch it this way in my controller:

我可以用我的控制器捕捉它:

 try {
     $this->insertThings->insertId("1");
 } catch (UserException $error){
     //do whatever you want when there is an mysql error

 }

#7


2  

Use it

使用它

    $this->db->_error_message(); 

It is better for finding error.After completing your site. Close the error messages using it

它更适合发现错误。在完成你的网站。使用它关闭错误消息

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

You will change it in your config folder's database.php

您将在配置文件夹的database.php中更改它

#8


2  

Put this code in a file called MY_Exceptions.php in application/core folder:

将此代码放入名为my_exception的文件中。php应用程序/核心文件夹中:

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Class dealing with errors as exceptions
 */
class MY_Exceptions extends CI_Exceptions
{

    /**
     * Force exception throwing on erros
     */
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        set_status_header($status_code);

        $message = implode(" / ", (!is_array($message)) ? array($message) : $message);

        throw new CiError($message);
    }

}

/**
 * Captured error from Code Igniter
 */
class CiError extends Exception
{

}

It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:

它将使所有的代码触发错误被视为异常(CiError)。然后,打开所有数据库调试:

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

#9


0  

If one uses PDO, additional to all the answers above.

如果你使用PDO,除了上面所有的答案。

I log my errors silently as below

我像下面这样默默地记录我的错误

        $q = $this->db->conn_id->prepare($query);

        if($q instanceof PDOStatement) {
           // go on with bind values and execute

        } else {

          $dbError = $this->db->error();
          $this->Logger_model->logError('Db Error', date('Y-m-d H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' -  '.'Message: '.$dbError['message']);

        }

#1


51  

Try these CI functions

试试这些词功能

$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)

#2


29  

Maybe this:

也许是这样的:

$db_debug = $this->db->db_debug; //save setting

$this->db->db_debug = FALSE; //disable debugging for queries

$result = $this->db->query($sql); //run query

//check for errors, etc

$this->db->db_debug = $db_debug; //restore setting

#3


22  

In Codeigniter 3.0 (CI3), all you have to do is $this->db->error()

在Codeigniter 3.0 (CI3)中,您所需要做的就是$this->db->error()

If you need to get the last error that has occured, the error() method will return an array containing its code and message

如果需要获取已发生的最后一个错误,error()方法将返回一个包含其代码和消息的数组

http://www.codeigniter.com/user_guide/database/queries.html#handling-errors

http://www.codeigniter.com/user_guide/database/queries.html处理错误

#4


14  

You must turn debug off for database in config/database.php ->

必须在配置/数据库中关闭数据库的调试。php - >

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

It is better for your website security.

这对你的网站安全更好。

#5


10  

I know this thread is old, but just in case there's someone else having this issue. This is a trick I used without touching the CI db classes. Leave your debug on and in your error view file, throw an exception.

我知道这条线是旧的,但是以防有人有这个问题。这是我在不接触CI db类的情况下使用的技巧。将调试留在错误视图文件中,抛出一个异常。

So in you db config, you have :

在你的db配置中,你有

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

Then in your db error view file, mine is in application/errors/error_db.php replace all content with the following:

然后在您的db错误视图文件中,我的是应用程序/错误/error_db。php将所有内容替换为以下内容:

<?php
$message = preg_replace('/(<\/?p>)+/', ' ', $message);
throw new Exception("Database error occured with message : {$message}");

?>

Since the view file will be called, the error will always get thrown as an exception, you may later add different views for different environment.

由于视图文件将被调用,错误将被作为一个异常抛出,您可以稍后为不同的环境添加不同的视图。

#6


4  

I have created an simple library for that:

我为此创建了一个简单的库:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class exceptions {

    public function checkForError() {
        get_instance()->load->database();
        $error = get_instance()->db->error();
        if ($error['code'])
            throw new MySQLException($error);
    }
}

abstract class UserException extends Exception {
    public abstract function getUserMessage();
}

class MySQLException extends UserException {
    private $errorNumber;
    private $errorMessage;

    public function __construct(array $error) {
        $this->errorNumber = "Error Code(" . $error['code'] . ")";
        $this->errorMessage = $error['message'];
    }

    public function getUserMessage() {
        return array(
            "error" => array (
                "code" => $this->errorNumber,
                "message" => $this->errorMessage
            )
        );
    }

}

The example query:

这个示例查询:

function insertId($id){
    $data = array(
        'id' => $id,
    );

    $this->db->insert('test', $data);
    $this->exceptions->checkForError();
    return $this->db->insert_id();
}

And I can catch it this way in my controller:

我可以用我的控制器捕捉它:

 try {
     $this->insertThings->insertId("1");
 } catch (UserException $error){
     //do whatever you want when there is an mysql error

 }

#7


2  

Use it

使用它

    $this->db->_error_message(); 

It is better for finding error.After completing your site. Close the error messages using it

它更适合发现错误。在完成你的网站。使用它关闭错误消息

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

You will change it in your config folder's database.php

您将在配置文件夹的database.php中更改它

#8


2  

Put this code in a file called MY_Exceptions.php in application/core folder:

将此代码放入名为my_exception的文件中。php应用程序/核心文件夹中:

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Class dealing with errors as exceptions
 */
class MY_Exceptions extends CI_Exceptions
{

    /**
     * Force exception throwing on erros
     */
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        set_status_header($status_code);

        $message = implode(" / ", (!is_array($message)) ? array($message) : $message);

        throw new CiError($message);
    }

}

/**
 * Captured error from Code Igniter
 */
class CiError extends Exception
{

}

It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:

它将使所有的代码触发错误被视为异常(CiError)。然后,打开所有数据库调试:

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

#9


0  

If one uses PDO, additional to all the answers above.

如果你使用PDO,除了上面所有的答案。

I log my errors silently as below

我像下面这样默默地记录我的错误

        $q = $this->db->conn_id->prepare($query);

        if($q instanceof PDOStatement) {
           // go on with bind values and execute

        } else {

          $dbError = $this->db->error();
          $this->Logger_model->logError('Db Error', date('Y-m-d H:i:s'), __METHOD__.' Line '.__LINE__, 'Code: '.$dbError['code'].' -  '.'Message: '.$dbError['message']);

        }