我搜索了很长时间(这里也是),阅读了很多php代码,但仍然找不到令人满意的答案。这似乎是一个太宽泛的话题,但它确实结合在一起——最后对我来说。能否请你帮忙?
在一个 php 网站中,我将 PDO 作为 DAL,BLL 对象使用什么,它们是从 UI 调用的。现在,如果发生了什么事,PDO 会抛出 PDOException。当然,UI 层不必知道任何关于 PDOExceptions 的信息,因此 BLL 对象会捕获它。但现在呢?
我读过
- 例外是针对真正特殊的情况和
- 一个从低层重新抛出异常,以免上层出现低级异常。
让我说明我的问题(请不要关注函数args):
class User
{
function signUp()
{
try
{
//executes a PDO query
//returns a code/flag/string hinting the status of the sign up:
//success, username taken, etc.
}
catch (PDOException $e)
{
//take the appropriate measure, e.g. a rollback
//DataAccessException gets all the information (e.g. message, stack
//trace) of PDOException, and maybe adds some other information too
//if not, it is like a "conversion" from PDOException to DAE
throw new DataAccessException();
}
}
}
//and in an upper layer
$user = new User();
try
{
$status = $user->signUp();
//display a message regarding the outcome of the operation
//if it was technically successful
}
catch (DataAccessException $e)
{
//a technical problem occurred
//log it, and display a friendly error message
//no other exception is thrown
}
这是一个正确的解决方案吗?重新抛出 PDOException 时,我认为不适合使用异常链接(因为这只会使调试信息变得多余;DataAccessException 获取所有内容,包括来自 PDOException 的完整堆栈跟踪)。
提前致谢。