我有异常类:
class MartbooksException extends Exception
{
public function __construct($msg)
{
parent::__construct($msg, 0, null);
echo $msg;
Kohana::$log->add(Log::ERROR, $msg);
}
}
Kohana::$log->add(Log::ERROR, $msg);
我要在应用程序/日志文件中写入日志吗?
这是好的解决方案吗?
最佳答案
要遵循Kohana风格,我建议您使用:
Class Martbooks_Exception Extends Kohana_Exception
作为声明,并将名称为
exception.php
的文件放在classes/martbooks
中。这遵循Kohana的风格。扩展
Kohana_Exception
而不是Exception
允许您沿以下方向使用变量替换throw new Martbooks_Exception ('this is a :v', array (':v' => 'variable', ));
至于定义
__construct()
方法,echo $msg;
部分不是解决错误处理的首选方法,任何回显都应在捕获异常的块中进行。在调用Kohana::$log->add()
的情况下,可能会发生同样的争论,但是如果您想记录每个Martbooks_Exception
,则您的解决方案是完全有效的。在这种情况下,我会将您的代码重写为:Class Martbooks_Exception Extends Kohana_Exception
{
public function __construct($message, array $variables = NULL, $code = 0)
{
parent::__construct ($message, $variables, $code);
Kohana::$log->add (Log::ERROR, __ ($message, $variables));
}
}
定义的
__construct()
符合Kohana_Exception
的__construct()
。我反对在构造函数中使用
Log::ERROR
级别进行日志记录的唯一异议是,它假定每个异常都是应用程序级错误,某些异常类型可能确实如此,但也可以用于表示其他含义。异常的确切含义应留给异常处理块。
关于php - 设置Kohana的错误记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8531363/