【发布时间】:2017-04-27 19:14:56
【问题描述】:
我目前正在为 CakePHP 中的应用程序执行自定义 ErrorHandler。 原因?好吧,机器人总是试图在您的服务器中查找内容,有时它们会引发异常和/或错误。
这个ErrorHandler的想法是过滤请求并使用适当的标头进行响应,并通过处理此类请求来防止进一步的请求损坏,并使其对用户客户端透明(因为它例如可能会影响 JavaScript).
还有什么比使用框架的功能更好的方法,对吧?
问题是由于这个 ErrorHandler 是静态使用的, 好吧,没有构造函数,所以没有任何东西继承任何东西,它没有 如果您实例化任何其他 CakePHP 对象,则无关紧要。
什么是使用 CakeResponse 对象的合适方法?
CakePHP 的配置:
app/Config/bootstrap.php:
App::uses('CustomErrorHandler', 'Lib');
app/Config/core.php:
// Error and exception handlers.
Configure::write('Error', array(
'handler' => 'CustomErrorHandler::handleError',
'level' => E_ALL & ~E_DEPRECATED,
'trace' => true
));
Configure::write('Exception', array(
'handler' => 'CustomErrorHandler::handleException',
'renderer' => 'ExceptionRenderer',
'log' => true
));
app/Lib/CustomErrorHandler.php:
... rest of class code ...
/**
* Named after convention: This method receives all CakePHP's
* errors and exceptions…
*
* @param array $e The exception object.
* @return mixed Returns the error handling or header redirection.
*/
public static function handleException($e)
{
$message = (string) $e->getMessage();
$code = (int) $e->getCode();
$file = (string) $e->getFile();
$line = (string) $e->getLine();
// If it's a Blacklist resource exception it will log it and redirect to home.
if (self::__isResourceException($message))
{
return self::__dismissError();
}
return parent::handleException($e);
}
/**
* This method redirects to home address using CakeResponse Object.
*
* @return mixed
*/
private static function __dismissError()
{
return (new CakeResponse)->header(array(
'Location' => self::$redirectUrl
));
}
}
更新 2:
将在 ExceptionRenderer 上尝试一个小层。
【问题讨论】:
-
您会在处理程序中的哪个位置调用
__dismissError()? -
@ndm 我更新了问题的代码块……
标签: php cakephp error-handling cakephp-2.7