以以下功能作为我想做的事的示例:
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()
。
我将如何去做?
创建您自己的异常类并创建用于将字符串附加到消息的方法。
<?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;
}
}
?>
大多数支持异常处理的面向对象的语言框架都意识到了对此主题的需求。您需要了解Exceptions不是发生的事情的logs。相反,它们在那里可以准确地指出错误发生的位置。
因此,不仅语法不正确,整个想法还违反了十二种OOD原则。您应该引入一个记录器类,该类将收集有关错误的信息,并使用异常来指出需要记录的events。
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);
}
为什么不使用单独的变量来保留消息?
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();
}
}
可能不值得上新班。只需捕获您的异常,然后在旧消息后添加一个新异常即可。
try {
/* Something which might fail */
} catch (Exception $e) {
$msg = "My custom message " . $e->getMessage();
throw(new \Exception($msg));
}