在CodeIgniter中,当发生异常时,经常要通知系统管理员,因此有必要在全局的高度上
捕捉异常,因此可以写一个hook,
比如在config目录的hook.php中,加入:
$hook['pre_controller'][] = array(
'class' => 'ExceptionHook',
'function' => 'SetExceptionHandler',
'filename' => 'ExceptionHook.php',
'filepath' => 'hooks'
);
然后在应用的hook目录下,编写ExceptionHook.php
<?php
class ExceptionHook
{
public function SetExceptionHandler()
{
set_exception_handler(array($this, 'HandleExceptions'));
}
public function HandleExceptions($exception)
{
$msg ='Exception of type \''.get_class($exception).'\' occurred with Message: '.$exception->getMessage().' in File '.$exception->getFile().' at Line '.$exception->getLine();
$msg .="\r\n Backtrace \r\n";
$msg .=$exception->getTraceAsString();
log_message('error', $msg, TRUE);
mail('dev-mail@example.com', 'An Exception Occurred', $msg, 'From: test@example.com');
}
?>
捕捉异常,因此可以写一个hook,
比如在config目录的hook.php中,加入:
$hook['pre_controller'][] = array(
'class' => 'ExceptionHook',
'function' => 'SetExceptionHandler',
'filename' => 'ExceptionHook.php',
'filepath' => 'hooks'
);
然后在应用的hook目录下,编写ExceptionHook.php
<?php
class ExceptionHook
{
public function SetExceptionHandler()
{
set_exception_handler(array($this, 'HandleExceptions'));
}
public function HandleExceptions($exception)
{
$msg ='Exception of type \''.get_class($exception).'\' occurred with Message: '.$exception->getMessage().' in File '.$exception->getFile().' at Line '.$exception->getLine();
$msg .="\r\n Backtrace \r\n";
$msg .=$exception->getTraceAsString();
log_message('error', $msg, TRUE);
mail('dev-mail@example.com', 'An Exception Occurred', $msg, 'From: test@example.com');
}
?>
本文介绍如何在CodeIgniter框架中实现全局异常处理,通过编写Hook来捕获并记录异常,同时发送邮件通知开发者。
313

被折叠的 条评论
为什么被折叠?



