tha*_*guy 4 php exception-handling kohana
我正在使用Kohana 3.3,我在这个论坛帖子中读到.
它说为了防止向最终用户显示堆栈跟踪,我需要覆盖Kohana_Exception :: _ handler()以执行与渗透错误不同的操作.这是否意味着覆盖Kohana_Exception并添加以下功能?
public static function _handler(Exception $e)
{
try
{
// Log the exception
Kohana_Exception::log($e);
// Generate the response
//instead of below line:
//$response = Kohana_Exception::response($e);
$response = //what do I do here, return a 404 page or custom 500 page?
return $response;
}
//rest of function
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,我该怎么回?
编辑:
bootstrap.php中
/**
* Attach the file write to logging. Multiple writers are supported.
*/
Kohana::$log->attach(new Log_File(APPPATH.'logs'));
/**
* Attach a file reader to config. Multiple readers are supported.
*/
Kohana::$config->attach(new Config_File);
/**
* Attach customer error handler if we are in production
*/
if(Kohana::$environment == Kohana::PRODUCTION || Kohana::$environment == Kohana::STAGING)
{
set_exception_handler(array('My_Exception', 'handler'));
throw new Exception('text'); //this works, if removed however my exception handler does not do anything
}
Run Code Online (Sandbox Code Playgroud)
My_Exception.php(在classes/My/Exception.php中)
<?php
class My_Exception extends Kohana_Exception
{
public static function handler(Exception $e)
{
try
{
// Log the exception
Kohana_Exception::log($e);
// Let's try and load an error View
$class = get_class($e);
if($class == 'HTTP_Exception_404')
{
$view = View::factory('errors/404');
$view->set('error_code', 404);
}
else
{
$view = View::factory('errors/general');
$view->set('error_code', $e->getCode()); // alternatively use $e->getCode()
$view->set('error_message', $e->getMessage()); // alternatively use $e->getMessage();
}
// Let's render the output and send it to the browser
$response = $view->render();
echo $response;
}
catch (Exception $e)
{
/**
* Things are going *really* badly for us, We now have no choice
* but to bail. Hard.
*/
// Clean the output buffer if one exists
ob_get_level() AND ob_clean();
// Set the Status code to 500, and Content-Type to text/plain.
header('Content-Type: text/plain; charset='.Kohana::$charset, TRUE, 500);
// This will output the Exceptiones error message
// You may want to display something else
echo $e->getMessage();
exit(1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我实际上已经对这个问题进行了相当多的调查,并且从头开始重写了我的asnwer,因为我对Kohana在这方面的行为有了更全面的了解.
为了达到你想要的目标,你需要做两件事:
更改默认错误View(in APPPATH/bootstrap.php):
/**
* Change default error View
*/
if(Kohana::$environment == Kohana::PRODUCTION || Kohana::$environment == Kohana::STAGING)
{
Kohana_Exception::$error_view = 'errors/general';
}
Run Code Online (Sandbox Code Playgroud)
请注意,您的模板文件必须使用与Kohana本地变量名称相同(且仅限于那些)变量名称,即:
通过以下步骤,您可以确保:
我测试了上面的方法,它对我来说就像一个魅力.
| 归档时间: |
|
| 查看次数: |
2024 次 |
| 最近记录: |