处理数据库错误
我在应用程序中使用 MVC 框架,因此当前当我在模型中使用数据库时检测到发生错误时,我会将异常抛出回控制器。
//db querying
//doing more db querying...
if (error)
throw new ApiException('Unable to connect to User database', 1, 500);
else if (another type of error)
throw new StampApiException('Could not retrieve the User', 12, 500);
return $user;
大多数时候,我发现这很好,因为我可以让控制器将错误打印到屏幕上,从而将所有错误代码等保留在模型中。但有时这会使代码变得非常混乱并且难以处理。
这是处理此类错误的好方法吗?或者有更好/更标准的方法吗?
I am using an MVC framework in my application, so currently when I detect an error has occurred while working with the database in my model, I am throwing exceptions back to the controller.
//db querying
//doing more db querying...
if (error)
throw new ApiException('Unable to connect to User database', 1, 500);
else if (another type of error)
throw new StampApiException('Could not retrieve the User', 12, 500);
return $user;
Most of the time I find this to be nice as I can just have the controller print the error to the screen, thus keeping all error codes etc... in the model. But at times this can make the code quite messy and harder to deal with.
Is this a good way to be handling such errors? Or is there a better/more standard way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我想说用户不需要知道问题是数据库、管理员密码还是内存。只需为用户提供一个技术错误页面,并将错误详细信息记录在服务器上,以供调试。
对于你所说的技术问题,最好是有一个集中处理来管理它们,即抛出一个错误页面。
通常的地方是控制器的调度程序。如果您使用框架,则应该存在此机制(例如 symfony)。
这样,您就不必在实际代码中弄乱这些异常。
就像您发现的那样,最好的策略是仅当您可以采取措施时才捕获异常。
例如:
调度员。所以你不会在代码中捕获它,而是让它传递给
集中处理
例如提出创作。所以你抓住了它。
Fisrt, I would say the user does not need to know if the problem is the database, the admin password or the memory. Just have a technical error page for the user, and log the error detail on the server, for your debug.
For the technical problems you are talking about, the best is to have a central treatment to manage them, i.e. throw an error page.
The usual place is the dispatcher of the controller. If you're using a framework, this mechanism should exist (symfony for example).
This way, you don't have to mess with these exceptions in your actual code.
Just like you found it, the best policy is to catch an exception only when you can do something about it.
For example :
dispatcher. So you don't catch it in your code en let it to the
central treatment
to propose creation for example. So you catch it.