将以下功能作为我想要做的示例:
public function save() {
$this->connect('wb');
try {
if(!$this->lock())
throw new Exception("Unable to acquire configuration locks");
if (!$backup = $this->backup())
throw new Exception("Failed to create configuration backup");
try {
if(!fwrite($this->_pointer, $this->dump("string")));
throw new Exception("Error occured while writing to configuration");
$this->unlock();
$this->disconnect();
} catch (Exception $e) {
if(rename ($backup, $this->_file))
$e .= PHP_EOL."Successfully restored configuration from backup";
else
$e .= PHP_EOL."Failed to restore configuration from backup";
$this->unlock();
$this->disconnect();
throw $e;
}
} catch (Exception $e) {
echo PHP_EOL, $e->getMessage();
}
}
我已嵌套try()
和catch()
语句。从最内层抛出一个异常并被捕获,然后我执行一些函数并抛出另一个异常。请注意我写$e .=
的位置,我知道这是不正确的语法。我想要做的是将字符串追加到例外的$e->getMessage()
。
我将如何做到这一点?
答案 0 :(得分:7)
创建自己的异常类并创建用于将字符串附加到消息的方法。
<?php
class SuperException extends Exception
{
public function AppendToMessage($msg)
{
// $this->message is inherited from Exception class,
// where it is protected field (member) of the class
$this->message .= $msg;
}
}
?>
答案 1 :(得分:1)
支持异常处理的大多数面向对象的语言框架都意识到了对这一主题的需求。您需要了解例外不是日志所发生的事情。相反,它们可以确切地指出错误发生的位置。
因此,不仅语法不正确,整个想法违反了十几个OOD原则。您应该引入一个记录器类,它可以随时收集有关错误的信息,并使用异常来查明需要记录的事件。
class ErrorLogger {
private $log;
public function __construct() {
$this->log = array();
}
public function log(Exception $e) {
array_push($this->log, $e->getMessage());
}
}
并在您的代码中进一步:
$logger = new ErrorLogger();
try {
:
} catch (Exception $e) {
$logger->log($e);
}
答案 2 :(得分:0)
为什么不使用单独的变量来保留消息?
public function save() {
$this->connect('wb');
$exceptionMessage = "";
try {
if(!$this->lock())
throw new Exception("Unable to acquire configuration locks");
if (!$backup = $this->backup())
throw new Exception("Failed to create configuration backup");
try {
if(!fwrite($this->_pointer, $this->dump("string")));
throw new Exception("Error occured while writing to configuration");
$this->unlock();
$this->disconnect();
} catch (Exception $e) {
if(rename ($backup, $this->_file))
$exceptionMessage .= PHP_EOL."Successfully restored configuration from backup";
else
$exceptionMessage .= PHP_EOL."Failed to restore configuration from backup";
$this->unlock();
$this->disconnect();
throw $e;
}
} catch (Exception $e) {
echo PHP_EOL. $exceptionMessage . PHP_EOL . $e->getMessage();
}
}
答案 3 :(得分:0)
可能不值得上新课。只需捕获您的异常,然后在旧消息后添加一个新异常即可。
try {
/* Something which might fail */
} catch (Exception $e) {
$msg = "My custom message " . $e->getMessage();
throw(new \Exception($msg));
}