에러/예외를 set_error_handler(), set_exception_handler()로 커스텀 처리 하기 > php

본문 바로가기
사이트 내 전체검색

php

에러/예외를 set_error_handler(), set_exception_handler()로 커스텀 처리 하기

페이지 정보

작성자 서방님 댓글 0건 조회 96회 작성일 13-03-07 11:39

본문

출처 : http://www.phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=57415&sca=%C7%D4%BC%F6&page=13

 

조금 무식하게 된 부분이 있으니 각자 상황에 맞게 수정을 해서 쓰시기 바랍니다.
이것은 set_error_handler, set_exception_handler으로 사용자화해서 사용하기 위한 것입니다.

이 코드를 사용하기 위해서는 "THEPAPER™ 님하는 멋쟁이!" 라는 문구가 들어간 글을 톡박에 올리시면 됩니다. 풋~

사용함에 있어 실제 서비스 되는 서버에서는 조금 무리가 있는 부분이 있으나 알아서 수정해서 쓰시고, 코딩 스타일과 에러/예외 처리의 방법적인 부분을 좀 맞춰서 써야 한다는게 흠이라면 흠입니다. 하지만, 개발 초기부터 적용해서 쓰신다면야 나름 장점이 있으리라고 생각도 해 봅니다.

그럼 들어갑니다~

----- // Debug.php 파일의 내용 -----
/*##############################################################################
FILE NAME : debug.php
CREATE DATE : 2007. 03. 17 오전 4:33:19
ENCODING : UTF-8
POWERED BY : ⓒ2007 THEPAPER™
--------------------------------------------------------------------------------
[ SVN REVISION INFORMATION ]
$Rev: 14 $
$Date: 2007-03-25 05:25:23 +0000 $
--------------------------------------------------------------------------------
[ FILE DISCRIPTION ]
예외처리나 에러 출력 방식을 커시터마이징 하는 함수들의 집합
에러 메시지 출력 관련 함수 포함
--------------------------------------------------------------------------------
[ STRUCTURE & REFERENCE ]

##############################################################################*/
/**
 * 커스템 에러 핸들링 함수
 * 함수 내에서 독자적인 유저 에러를 표시하려면,
 * trigger_error("error title", {[E_USER_ERROR | E_USER_NOTICE | E_USER_WARNING]}) 식으로 사용
 *
 * @param int $errno 에러코드
 * @param string $errmsg 에러메시지
 * @param string $filename 에러파일명
 * @param int $linenum 에러라인
 * @param array $vars 환경변수
 * @return str
 */
function ErrorHandler($errno, $errmsg, $filename, $linenum, $vars){
// 치명적인 에러가 아니면 일단 건너 뛰기
// > 모든 에러 메시지를 받고 싶으면, 이 부분 주석처리 - 골치 아플껄~
if($errno == 8){
return FALSE;
}

// 에러타입 정의 - 전체 구성
$errortype = array(
E_ERROR,
E_WARNING,
E_PARSE,
E_NOTICE,
E_CORE_ERROR,
E_CORE_WARNING,
E_COMPILE_ERROR,
E_COMPILE_WARNING,
E_USER_ERROR,
E_USER_WARNING,
E_USER_NOTICE,
E_ALL,
E_STRICT
);
// 에러타입에 따른 출력 메시지
$errortype_str = array(
E_ERROR          => 'E_ERROR(1)',
E_WARNING        => 'E_WARNING(2)',
E_PARSE          => 'E_PARSE(4)',
E_NOTICE          => 'E_NOTICE(8)',
E_CORE_ERROR      => 'E_CORE_ERROR(16)',
E_CORE_WARNING    => 'E_CORE_WARNING(32)',
E_COMPILE_ERROR  => 'E_COMPILE_ERROR(64)',
E_COMPILE_WARNING => 'E_COMPILE_WARNING(128)',
E_USER_ERROR      => 'E_USER_ERROR(256)',
E_USER_WARNING    => 'E_USER_WARNING(512)',
E_USER_NOTICE    => 'E_USER_NOTICE(1024)',
E_ALL            => 'E_ALL(2047)',
E_STRICT          => 'E_STRICT(2048)'
);

// 메시지가 출력되어야할 에러들
$error_emer = array(
E_ERROR,
E_PARSE,
E_CORE_ERROR,
E_CORE_WARNING,
E_COMPILE_ERROR,
E_COMPILE_WARNING
);

// 유저에러 - 별도 처리
$user_errors = array(
E_USER_ERROR,
E_USER_WARNING,
E_USER_NOTICE
);
// 치명적인 에러가 아닌 에러들
$error_lv_low = array(
E_WARNING,
E_NOTICE,
E_STRICT
);
// 에러타입에 따른 처리

// 치명적인 에러의 경우 Exception Handler로 상세정보 표시
if(in_array($errno, $error_emer)){
try{
throw new Exception("{$errmsg}:<br />{$filename} at line {$linenum}<br />[{$errno} : {$errortype_str[$errno]}]", $errno);
}catch(Exception $e){
// $msg_sbj 처리
$msg_sbj['type'] = 'EX';
$msg_sbj['code'] = $errortype_str[$errno];
// $msg_cont 처리
$msg_cont['title'] = '유형:'.$e->getCode().'의 오류가 발생 했어요.';
$msg_cont['err_file'] = $filename;
$msg_cont['err_line'] = $linenum;
$msg_cont['err_msg'] = $e->getMessage();
$msg_cont['err_trace'] = $e->getTraceAsString();

}
// 메시지 날리기
debug_msg($msg_sbj, $msg_cont, TRUE);
return FALSE;
// 유저에러인 경우 그냥 Error Handler로 처리
}elseif(in_array($errno, $user_errors)){
// $msg['sbj'] 처리
$msg_sbj['type'] = 'ER';
$msg_sbj['code'] = $errortype_str[$errno];
// $msg['cont'] 처리
$msg_cont['title'] = '유형:'.$errortype_str[$errno].'의 오류가 발생 했어요.';
$msg_cont['err_file'] = $filename;
$msg_cont['err_line'] = $linenum;
$msg_cont['err_msg'] = $errmsg;
// 메시지 날리기
debug_msg($msg_sbj, $msg_cont, TRUE);
return FALSE;
// 낮은 레벨의 에러의 경우
}elseif(in_array($errno, $error_lv_low)){
// 일단은 암것도 안보여 준다... 아님 보이게 하든가~
return FALSE;
}
return FALSE;
}

/**
 * 커스텀 예외처리 핸들링 함수
 * 클래스에서 예외 발생시 처리됨
 * 독자적인 예외를 두려면
 * try, catch 사용
 */
function ExceptionHandler($message = NULL, $code = 0){
// $msg['sbj'] 처리
$msg_sbj['type'] = 'EX';
$msg_sbj['code'] = $message->getCode();
// $msg['cont'] 처리
$msg_cont['title'] = '유형:'.$msg_sbj['code'].'의 오류가 발생 했어요.';
$msg_cont['err_file'] = $message->getfile();
$msg_cont['err_line'] = $message->getline();
$msg_cont['err_msg'] = $message->getMessage();
$msg_cont['err_trace'] = $message->getTraceAsString();
// 최종 메시지 출력
//if($msg_sbj['code'] != 8 && $msg_sbj['code'] != 2){
debug_msg($msg_sbj, $msg_cont, TRUE);
//}
}

/**
 * 디버그용 에러, 예외 출력
 * 기타 시스템 기반의 메시지 출력용
 *
 * @param array|string $sbj 제목 표시
 * @param array|string $cont 세부내용 표시
 * @param bool $break 메시지 출력후 죽는지 여부, 기본은 죽어버림.
 */
function debug_msg($sbj, $cont, $break=TRUE){ // FIXME 디버그 관련 모든 사항 추적해서 클린 할것!!! 예외처리나 변수 컨트롤 조낸 안했음!!!
// $sbj 처리 - 배열[type, code], 문자열, 공백일수 있다.
if($sbj != ''){ // $sbj가 비어있지 않은경우
$sbj_str = '';
if(is_array($sbj)){ // $sbj를 배열로 받은 경우
// 에러인지 예외인지 판단
if($sbj['type'] == 'ER'){ // 에러로 처리
$sbj_str = '(x_x) [에러발생] - ';
}elseif($sbj['type'] == 'EX'){ // 예외로 처리
$sbj_str = '(o_o) [예외발생] - ';
}
// 에러코드
$sbj_str .= $sbj['code'];
}else{
$sbj_str = '(?!)'.$sbj; // 일반 문자열로 들어올 경우 그냥처리
}
}else{ // $sbj가 텅~ 비어서 들어올 경우
$sbj_str = '(-_-;) 저도 모르는 오류가 발생 했어요.';
}
// $cont 처리
/*
$cont가 배열로 들어오는 경우 체크할 것들
$cont['title'] 처음의 안내 문구 - 에러에 대한 총체적인 요약
$cont['sql'] sql 에러의 경우 에러난 sql문을 가져와 query_beautify로 다듬는다.
$cont['err_file'] 에러난 파일 - 계정 루트로 부터의 경로만 보여준다. 계정 루트는 [ACCOUNT ROOT]로 표기
$cont['err_line'] 에러난 줄 번호 - TODO 나중에 해당 파일을 읽어와서 해당 줄 전후의 몇줄을 출력해 주면 좋겠다...
$cont['err_msg'] 에러 메시지
$cont['err_trace'] 추적
*/

if(is_array($cont)){ // $cont가 배열로 들어올때
// $cont['sql']
//if($cont['sql']){
// $cont['sql'] = query_beautify($cont['sql']);
//}
// $cont['err_msg']
$cont['err_msg'] = str_replace($_SERVER['DOCUMENT_ROOT'], '', str_replace('\\', '/', $cont['err_msg']));
// $cont['err_file']
if($cont['err_file']){
$cont['err_file'] = str_replace($_SERVER['DOCUMENT_ROOT'], '', str_replace('\\', '/', $cont['err_file']));
$cont['err_file'] = '<span style="color:#339900;">[ACCOUNT ROOT]</span>'.$cont['err_file'];
}
// $cont['err_line']
if($cont['err_line']){
$cont['err_line'] = $cont['err_line'].' 번 라인';
}
// $cont['err_trace']
if($cont['err_trace']){
$cont['err_trace'] = nl2br(str_replace($_SERVER['DOCUMENT_ROOT'], '', str_replace('\\', '/', $cont['err_trace'])));
$cont['err_trace'] = ereg_replace('(#[0-9]+)', '<span style="color:#ffffff;"><span style="color:#FF3000;">\\1</span><br /></span>', $cont['err_trace']);
}
}else{ // $cont가 비어 있거나 배열이 아닐때
//$cont['err_msg'] = $cont;
}
// 스킨에 입히기
ob_start();
include('Debug.skin.php');
$debug_msg = ob_get_contents();
ob_end_clean();
echo $debug_msg;
// $break
if($break){
exit;
}
}

/**
 * debug_msg에 sql문이 들어가면 다듬어서 이쁘게 보여주기
 * !!! 모든 sql문의 명령어는 대문자로 한다!!!
 *
 * @param string $sql sql문
 * @return string
 */
function query_beautify($sql){
// End Of Line 정의. 혹시나 해서~
if(strstr(PHP_OS, 'WIN')){
$EOL = '\r\n';
}else{
$EOL = '\n';
}
$sql = str_replace($EOL, "", $sql);
$sql = str_replace("\t", "", $sql);
$sql = str_replace("SET", "SET<br /> ", $sql);
$sql = str_replace(",", ",<br /> ", $sql);
$sql = str_replace("WHERE", "<br />WHERE", $sql);
$sql = ereg_replace("([^A-Z]+)", "<span style=\"color:#3366CC;\">\\1</span>", $sql);
return $sql;
}
----- Debug.php 파일의 내용 끝 // -----

----- // Debug.skin.php 파일의 내용 -----
/*##############################################################################
FILE NAME : debug.skin.php
CREATE DATE : 2007. 03. 17 오전 4:52:30
ENCODING : UTF-8
POWERED BY : ⓒ2007 THEPAPER™
--------------------------------------------------------------------------------
[ SVN REVISION INFORMATION ]
$Rev: 5 $
$Date: 2007-03-24 19:59:18 +0000 $
--------------------------------------------------------------------------------
[ FILE DISCRIPTION ]
디버그 메시지가 출력되는 모양을 정의 하는 스킨
알맹이만 있어효~
--------------------------------------------------------------------------------
[ STRUCTURE & REFERENCE ]
debug_msg()에서 인클루드 되어 출력된다.
##############################################################################*/
?>
<!-- // DEBUG STYLE -->
<style type="text/css">
<!--
.debug_full_stage{width:90%; height:auto; min-width:300px; border:none; border-collapse:collapse;}
.debug_title{width:100%; height:20px; border:none; border-collapse:collapse;}
.debug_title_1{
width:25px;
height:20px;
background:url(/img/bg.debug.title.01.gif) no-repeat top left;
}
.debug_title_2{
width:auto;
height:20px;
padding-top:3px;
background:url(/img/bg.debug.title.02.gif) repeat-x top left;
font:normal 11px/11px '돋움체', DotumChe, monospace;
color:#FFFFFF;
letter-spacing:0px;
word-spacing:2px;
}
.debug_title_3{
width:44px;
height:20px;
background:url(/img/bg.debug.title.03.gif) no-repeat top left;
}
.debug_cont{width:100%; height:auto; border:none; border-collapse:collapse;}
.debug_cont_1{
width:5px;
height:auto;
background:url(/img/bg.debug.cont.01.gif) repeat-y top left;
}
.debug_cont_2{
width:auto;
height:auto;
padding:5px 0px;
background:#F5F5F5;
text-align:left;
font:normal 11px/14px '돋움체', DotumChe, monospace;
color:#555555;
letter-spacing:0px;
word-spacing:2px;
}
.debug_cont_3{
width:5px;
height:auto;
background:url(/img/bg.debug.cont.02.gif) repeat-y top right;
}
.debug_bottom{width:100%; height:10px; border:none; border-collapse:collapse;}
.debug_bottom_1{
width:5px;
height:10px;
background:url(/img/bg.debug.btm.01.gif) no-repeat top left;
}
.debug_bottom_2{
width:auto;
height:10px;
background:#555555;
font-size:1px;
color:#555555;
}
.debug_bottom_3{
width:125px;
height:auto;
background:url(/img/bg.debug.btm.02.gif) no-repeat top right;
}
.debug_btn_back{
cursor:pointer;
width:17px;
height:20px;
background:url(/img/btn.debug.back.gif) no-repeat 0px 0px;
}
.debug_btn_back_hover{
cursor:pointer;
width:17px;
height:20px;
background:url(/img/btn.debug.back.gif) no-repeat 0px -20px;
}
.debug_btn_close{
cursor:pointer;
width:17px;
height:20px;
background:url(/img/btn.debug.close.gif) no-repeat 0px 0px;
}
.debug_btn_close_hover{
cursor:pointer;
width:17px;
height:20px;
background:url(/img/btn.debug.close.gif) no-repeat 0px -20px;
}
.debug_btn_zone{width:44px; height:20px; border:none; border-collapse:collapse;}
.debug_btn_gab{width:5px; height:20px; font-size:1px;}
.debug_cont_sec_title{
background:url(/img/title.debug.Cimg.02.gif) repeat-x top left;
padding:2px;
color:#FFFFFF;
}
.debug_cont_sec_title_p{
margin:5px 10px;
}
-->
</style>
<!-- // DEBUG STYLE -->
<!-- // DEBUG FULL STAGE -->
<table align="center" cellpadding="0" cellspacing="0" class="debug_full_stage">
<tr>
<td>
<!-- // TITLE BAR -->
<table cellpadding="0" cellspacing="0" class="debug_title">
<tr>
<td class="debug_title_1"><!--SPACER--></td>
<td class="debug_title_2"><?=$sbj_str;?></td>
<td class="debug_title_3">
<!-- // TITLE BAR BUTTON -->
<table cellpadding="0" cellspacing="0" class="debug_btn_zone">
<tr>
<td class="debug_btn_back"  title="뒤로가기"
onMouseover="this.className='debug_btn_back_hover';"
onMouseout="this.className='debug_btn_back';"
onClick="document.location.href=';"><!-- // BACK BUTTON // --></td>
<td class="debug_btn_gab"><!--SPACER--></td>
<td class="debug_btn_close"  title="현재창 강제종료"
onMouseover="this.className='debug_btn_close_hover';"
onMouseout="this.className='debug_btn_close';"
onClick="document.location.href=';"><!-- // CLOSE BUTTON // --></td>
<td class="debug_btn_gab"><!--SPACER--></td>
</tr>
</table>
<!-- // TITLE BAR BUTTON -->
</td>
</tr>
</table>
<!-- // TITLE BAR -->
</td>
</tr>
<tr>
<td>
<!-- // CONTENT -->
<table cellpadding="0" cellspacing="0" class="debug_cont">
<tr>
<td class="debug_cont_1"><!--SPACER--></td>
<td valign="top" class="debug_cont_2">
<!-- // MESSAGE -->
<?if($cont['title']){ // title?>
<img align="absmiddle" src="/img/title.debug.Cimg.01.gif"
style="width:8px; height:16px; border:none;" /><span class="debug_cont_sec_title">요약정보</span><img
align="absmiddle" src="/img/title.debug.Cimg.03.gif"
style="width:8px; height:16px; border:none;" />
<p class="debug_cont_sec_title_p">
<?=$cont['title'];?>
</p>
<div style="display:block; width:100px; height:10px; font-size:1px;"><!--//SPACER//--></div>
<?}?>
<?if($cont['sql']){ // sql?>
<img align="absmiddle" src="/img/title.debug.Cimg.01.gif"
style="width:8px; height:16px; border:none;" /><span class="debug_cont_sec_title">MySql Query</span><img
align="absmiddle" src="/img/title.debug.Cimg.03.gif"
style="width:8px; height:16px; border:none;" />
<p class="debug_cont_sec_title_p">
<?=$cont['sql'];?>
</p>
<div style="display:block; width:100px; height:10px; font-size:1px;"><!--//SPACER//--></div>
<?}?>
<?if($cont['err_msg']){ // err_msg?>
<img align="absmiddle" src="/img/title.debug.Cimg.01.gif"
style="width:8px; height:16px; border:none;" /><span class="debug_cont_sec_title">메시지</span><img
align="absmiddle" src="/img/title.debug.Cimg.03.gif"
style="width:8px; height:16px; border:none;" />
<p class="debug_cont_sec_title_p">
<?=$cont['err_msg'];?>
</p>
<div style="display:block; width:100px; height:10px; font-size:1px;"><!--//SPACER//--></div>
<?}?>
<?if($cont['err_file']){ // err_file?>
<img align="absmiddle" src="/img/title.debug.Cimg.01.gif"
style="width:8px; height:16px; border:none;" /><span class="debug_cont_sec_title">해당파일</span><img
align="absmiddle" src="/img/title.debug.Cimg.03.gif"
style="width:8px; height:16px; border:none;" />
<p class="debug_cont_sec_title_p">
<?=$cont['err_file'];?>
</p>
<div style="display:block; width:100px; height:10px; font-size:1px;"><!--//SPACER//--></div>
<?}?>
<?if($cont['err_line']){ // err_line?>
<img align="absmiddle" src="/img/title.debug.Cimg.01.gif"
style="width:8px; height:16px; border:none;" /><span class="debug_cont_sec_title">에러라인</span><img
align="absmiddle" src="/img/title.debug.Cimg.03.gif"
style="width:8px; height:16px; border:none;" />
<p class="debug_cont_sec_title_p">
<?=$cont['err_line'];?>
</p>
<div style="display:block; width:100px; height:10px; font-size:1px;"><!--//SPACER//--></div>
<?}?>
<?if($cont['err_trace']){ // err_trace?>
<img align="absmiddle" src="/img/title.debug.Cimg.01.gif"
style="width:8px; height:16px; border:none;" /><span class="debug_cont_sec_title">에러추적</span><img
align="absmiddle" src="/img/title.debug.Cimg.03.gif"
style="width:8px; height:16px; border:none;" />
<p class="debug_cont_sec_title_p">
<?=$cont['err_trace'];?>
</p>
<div style="display:block; width:100px; height:10px; font-size:1px;"><!--//SPACER//--></div>
<?}?>
<!-- MESSAGE // -->
</td>
<td class="debug_cont_3"><!--SPACER--></td>
</tr>
</table>
<!-- CONTENT // -->
</td>
</tr>
<tr>
<td>
<!-- // BOTTOM BAR -->
<table cellpadding="0" cellspacing="0" class="debug_bottom">
<tr>
<td class="debug_bottom_1"><!--SPACER--></td>
<td class="debug_bottom_2"> . </td>
<td class="debug_bottom_3"><!--SPACER--></td>
</tr>
</table>
<!-- BOTTOM BAR // -->
</td>
</tr>
</table>
<!-- // DEBUG FULL STAGE -->
----- Debug.skin.php 파일의 내용 끝 // -----

이제 기본 설정 부분 입니다.
아마도 대부분은 common.php식으로 공통으로 쓰이는 부분을 따로 마련해 놓으시겠죠.

error_reporting(E_ALL ^ E_NOTICE); // 일단 이렇게 하든가, 아니면 구미에 맞게 설정하세요. 별로 중요하진 않아요~

// php환경 설정
ini_set('display_errors', 0); // 에러 화면에 출력 안되게
ini_set('ignore_repeated_errors', 1); // 반복되는 중복 에러는 무시
ini_set('ignore_repeated_source', 1); // 반되는 중복 소스는 무시
ini_set('html_errors', 0); // 에러를 HTML형식으로 안나타나게

// 헤더 설정~
// 블라블라~ 뭐시기 코드들~~

include_once("경로/debug.php"); // 디버그 출력용 라이브러리

// !!! 이게 젤로 중요!!!
// 커스텀 예외처리 및 에러 핸들러 정의를 위한 구성
set_error_handler("ErrorHandler"); // 사용자 에러 핸들러 정의
set_exception_handler("ExceptionHandler"); // 사용자 예외처리 정의

이렇게 해서 기본적인 사용 환경 구성은 다 되었습니다!!!
이제 활용/응용을 해 볼까염~?

우선적으로 PHP상의 에러 메시지가 출력될 상황이면 커스텀 핸들러가 알아서 처리를 하고 스킨에 입혀서 출략해 줍니다. 에러나 예외의 중요도에 다라서 더이상 코드의 실행이 안되게도 하구요.

예를 들어, print_r($_POST); 를 primt_r($_POST);라고 하면 primt_r이라는 함수는 없으므로 알아서 에러 메시지를 에러 핸들러거 잡아서 가공하고 뿌려 줍니다. 이건 Fatal Error이므로 이후의 코드는 더이상 실행이 안되게 이 에러가 잡힌 부분에서 exit;처리 됩니다.

이제 예외 처리의 방법을 알아 볼까요? 간단히 DB 접속 함수에 위 핸들러를 사용해 봅시다. DB접속 함수(쬐끔 쎄련되게~ mysqli를 썼슴돠~)를 보시죠.

/**
 * DB 접속 및 DB 선택(mysqli OOP 사용) DB 정보 파일 까지 처리
 * @global $DBCONN object
 * @return object
 */
function dbconn(){
global $DBCONN;
if(!file_exists('경로/dbconfig.php')){
try{
throw new Exception('dbconfig.php 파일을 찾을 수 없어요.<br />설치시 "dbconfig.php"파일이 생성되지 않았거나 이름이 바뀐경우 DB연결을 할 수 없어요.');
}catch(Exception $e){
echo $e->getMessage();
}
}
include_once(.'경로/dbconfig.php'); // dbconfig.php안에 접속 정보 있음
if(!$DBCONN){
$DBCONN = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_db);
if(mysqli_connect_errno()){ // 접속에 실패 했다면,
try{
throw new Exception('DB 접속에 실패 했어요.');
}catch(Exception $e){
echo $e->getMessage();
echo "<br /><br />[에러코드]<br />".mysqli_connect_errno()."<br /><br />
[에러메시지]<br />".iconv("CP949", "utf-8//IGNORE", mysqli_connect_error())."<br /><br />";
}
}else{ // 접속에 성공 했다면,
$DBCONN->query("SET NAMES utf8");
$DBCONN->query("SET CHARACTER SET utf8");
$DBCONN->query("SET SESSION collation_connection = 'utf8_general_ci'");
}
}
return $DBCONN;
}

이 함수가 있고,
$DBCONN = dbconn();
이렇게 했을때,
dbconfig.php파일의 유무에 따라 if(!file_exists('경로/dbconfig.php')){try{} 부분에서 처리 됩니다. 아... try{}catch(Exception $e){}의 사용에 대해서 까리는 분들이 있으시고, 코딩 스타일이나 사용성에 대해서 논하시는 분들이 있는데요. 뭐.. 제가 보기엔 잘 되고, 엄하게 리소스 안잡아 먹으면 그냥 씁니다.

또 하나, 쿼리 날리는 함수를 예로 들어 보죠...

/**
 * 일반 쿼리
 *
 * @param $sql str 쿼리문
 * @param $debug bool 에러메시지 출력여부
 * @global $DBCONN object
 * @return object
 */
function sql_query($sql, $debug = TRUE){
global $DBCONN;
if(!$DBCONN){ // DB 접속 객체가 생성되지 않았다면,
if($debug == TRUE){
debug_msg(
"DB 접속도 안했어요.",
"DB 접속도 안했는데 무슨 쿼리를 날리려고..."
);
}
}
$result = $DBCONN->query($sql); // 쿼리
if($DBCONN->error && $debug == TRUE){ // 에러 발생시
try{
throw new Exception($DBCONN->error, $DBCONN->errno);
}catch(Exception $e){
// $msg_sbj 처리
$msg_sbj['type'] = 'ER';
$msg_sbj['code'] = $e->getCode();
// $msg_cont 처리
$msg_cont['title'] = '다음 쿼리문에 문제가 있어요. 유형:'.$msg['sbj']['code'];
$msg_cont['sql'] = $sql;
$msg_cont['err_file'] = $e->getfile();
$msg_cont['err_line'] = $e->getline();
$msg_cont['err_msg'] = iconv("CP949", "utf-8//IGNORE", $e->getMessage());
$msg_cont['err_trace'] = $e->getTraceAsString();
// 최종 메시지 출력
debug_msg($msg_sbj, $msg_cont, TRUE);
}
}
return $result;
}

어때요~ 참 쉽죠?
debug_msg() 함수가 좀 무식하게 꾸성되긴 했지만... -_-;;
쿼리문 중에서 에러가 나면 debug_msg()를 통해 에러난 쿼리문도 보여주고, 어떤 파일의 몇 번째 줄에서 ExceptionHandler가 호출 되었는지, 또 include된 파일이라면 그 include된 파일들까지 추적(?)해서 해당 파일과 해당 라인 수를 출력해 줍니다.
어때요~ 참 쉽죠? -_-;;

또 한 예로는 trigger_error()의 사용 입니다.
사용자가 예외를 발생 시키거나 어떤 부분에서 예외 발생시 의도적으로 실행을 중단하고, 에러화면을 출력해야 할때,
trigger_error('에러 타이틀(제목)', E_USER_ERROR) 식으로 사용하거나,
trigger_error('에러 타이틀(제목)', '에러내용~');
이러면 또 알아서 잘 뿌려 줍니다.
뭐 이런식으로도 사용할 수도 있습니다.

각 함수를 좀더 다듬고 응용을 하면 에러나 예외 발생시에 그 정도나 특성애 따라 다양한 커스텀 핸들링이 가능 하겠습니다.

댓글목록

등록된 댓글이 없습니다.

Total 612건 29 페이지
게시물 검색

회원로그인

접속자집계

오늘
236
어제
225
최대
1,347
전체
154,995
Latest Crypto Fear & Greed Index

그누보드5
Copyright © 서방님.kr All rights reserved.