【发布时间】:2013-05-29 18:47:36
【问题描述】:
我的 php 应用程序中有一个 try-catch 块,如下所示:
try {
if ($userForgotToEnterField) {
throw new Exception('You need to fill in your name!');
}
...
doDifferentThingsThatCanThrowExceptions();
...
} catch (ExpectedException $e) {
$template->setError('A database error occured.');
} catch (Exception $e) {
$template->setError($e->getMessage());
}
我只想输出 $e->getMessage() 用于我手动抛出的带有自定义错误文本的异常,而不是其他代码抛出的异常,因为这些可能包含敏感信息或用户应该使用的非常技术信息没看到。
是否可以在不使用自定义异常类的情况下区分手动抛出的异常和某些方法抛出的随机异常?
【问题讨论】:
-
我看不出有人想要这个,但你可以在抛出异常时设置一个全局变量来区分它们
-
您可以扩展 Exceptions 类,然后捕获您的自定义 Exceptions php.net/manual/en/language.exceptions.extending.php
-
好吧,我的项目中真的不需要自定义异常类。那我为什么要使用一个呢?这会产生不必要的复杂性。感谢您对全局变量的建议,但我认为这会造成更多的混乱。
-
但是 OP 请求没有自定义异常(如果可能的话)
-
@Zulakis:为这个场景添加自定义异常,不会让你的代码更复杂;它相当简化了它(特别是对于其他期望它的开发人员)
标签: php exception exception-handling try-catch