php异常处理的自定义消息


Custom messages for php exception handling

我使用一个带有$errmsg数组的外部文件来显示错误,比如:

'app_init' => 'Cannot initialize application',

使用条件语句,我调用函数来显示故障消息:

if(!$condition)
{
$arraywithmessages->functionforfiltering($err,'app_init',$aim);
}

其中$err是消息数组,$aim是发布错误的预定义方法(电子邮件、视图等)

现在我想利用异常处理,但我不知道从哪里开始。有人能帮忙吗?这似乎不起作用:

try {
if (!$condition) {
throw new Exception('app_init');
}
// continue
} catch (Exception $e) {
$arraywithmessages->functionforfiltering($err,$e->getMessage(),$aim);
}

我不知道你到底想要实现什么,但你应该记住,try,catch应该明智地使用。它只能用于特殊情况。如果你不以这种方式使用它们,那么这就是GOTO代码。

关于异常,请注意,您可以扩展Exception类并创建自己的异常,并在多个catch块中捕获它们,还有finally块。

关于Exception的构造函数。它有第二个参数$code,您可以使用它来显示正确的消息。

$err = array(0x1 => 'my error app init');
try {
if (!$condition) {
    throw new Exception('app_init', 0x1);
}
// continue
} catch (Exception $e) {
  echo $err[$e->getCode()]; //it shouldn't be only echo it should do some tries to fix the code close streams etc. not just echo.
}

还有功能set_exception_handler().哪个:

如果在try/catch块中未捕获到异常,则设置默认的异常处理程序。调用exception_handler后,执行将停止。

考虑使用它。在手册中可以找到很多东西。