CodeIgniter-DB 오류를 잡는 방법?
다음 과 같은 메시지를 표시하는 대신 DB 오류 가 발생했을 때 CI 가 예외를 throw 하도록하는 방법이 있습니까?
데이터베이스 오류 발생 오류 번호 : 1054 'where 절'의 알 수없는 열 'foo'SELECT * FROM (
FooBar
) WHEREfoo
= '1'
참고 : 하나의 컨트롤러에서만이 작업이 수행되기를 원합니다. 다른 컨트롤러에서는 DB 오류 메시지 가 표시되어 기쁩니다 .
다음 CI 기능 시도
$this->db->_error_message(); (mysql_error equivalent)
$this->db->_error_number(); (mysql_errno equivalent)
아마도 이것은 :
$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
Codeigniter 3.0 (CI3)에서해야 할 일은 $this->db->error()
발생한 마지막 오류를 가져와야하는 경우 error () 메서드는 코드와 메시지가 포함 된 배열을 반환합니다.
http://www.codeigniter.com/user_guide/database/queries.html#handling-errors
config / database.php->에서 데이터베이스에 대한 디버그를 해제해야합니다.
$db['default']['db_debug'] = FALSE;
웹 사이트 보안에 더 좋습니다.
이 스레드가 오래되었다는 것을 알고 있지만 다른 사람이이 문제를 겪고있는 경우를 대비하여. 이것은 CI db 클래스를 건드리지 않고 사용한 트릭입니다. 디버그를 켜고 오류보기 파일에서 예외를 발생시킵니다.
따라서 db 구성에는 다음이 있습니다.
$db['default']['db_debug'] = true;
그런 다음 db 오류보기 파일에서 내 application/errors/error_db.php
모든 내용을 다음으로 바꿉니다.
<?php
$message = preg_replace('/(<\/?p>)+/', ' ', $message);
throw new Exception("Database error occured with message : {$message}");
?>
보기 파일이 호출되기 때문에 오류는 항상 예외로 발생하므로 나중에 다른 환경에 대해 다른보기를 추가 할 수 있습니다.
이를 위해 간단한 라이브러리를 만들었습니다.
<?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
)
);
}
}
예제 쿼리 :
function insertId($id){
$data = array(
'id' => $id,
);
$this->db->insert('test', $data);
$this->exceptions->checkForError();
return $this->db->insert_id();
}
그리고 내 컨트롤러에서 이런 식으로 잡을 수 있습니다.
try {
$this->insertThings->insertId("1");
} catch (UserException $error){
//do whatever you want when there is an mysql error
}
이 코드를 application / core 폴더의 MY_Exceptions.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:
$db['default']['db_debug'] = true;
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
an example that worked for me:
$query = "some buggy sql statement";
$this->db->db_debug = false;
if(!@$this->db->query($query))
{
$error = $this->db->error();
// do something in error case
}else{
// do something in success case
}
...
Best
Disable debugging of errors.
$data_user = $this->getDataUser();
$id_user = $this->getId_user();
$this->db->db_debug = false;
$this->db->where(['id' => $id_user]);
$res = $this->db->update(self::$table, $data_user['user']);
if(!$res)
{
$error = $this->db->error();
return $error;
//return array $error['code'] & $error['message']
}
else
{
return 1;
}
If one uses PDO, additional to all the answers above.
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']);
}
참고URL : https://stackoverflow.com/questions/7843406/codeigniter-how-to-catch-db-errors
'IT Share you' 카테고리의 다른 글
Visual Studio 2010 웹 배포 작업이 실패했습니다. (0) | 2020.11.19 |
---|---|
TypeError : 'RelatedManager'개체는 반복 할 수 없습니다. (0) | 2020.11.19 |
유효하지 않은 문자는 어디에 있습니까 (ORA-00911) (0) | 2020.11.19 |
Jenkins Git 플러그인 분리 HEAD (0) | 2020.11.19 |
clang에 의한 C ++ 과부하 가상 함수 경고? (0) | 2020.11.19 |