使用服务层在分层应用程序中的何处抛出异常?
我想知道我应该在 Zend Framework + Doctrine 2 MVC 应用程序中的哪里抛出、捕获异常。
这是我的设计:
数据库 - MySQL > ORM (Doctrine2) >服务>控制器
我的服务将服务对象作为参数,并为几乎所有方法返回服务响应对象。
服务响应返回状态、消息和数据,可以是您想要的任何内容。
我的控制器使用这些服务。
我想知道我应该在哪里抛出异常。
示例:
public function getAllMembers(ServiceObject $data)
{
// do some mapping with $data
$users = $userRepository->getAllMembers($data);
$response = new ServiceResponse('success');
$response->setData($users);
return $response;
}
我应该检查服务中的参数,然后抛出一个控制器可以捕获的异常,还是应该抛出一个异常,比如说这个示例的存储库,并捕获我的服务以允许我返回带有以下内容的 ServiceResponse错误状态?
对于这种架构有什么反馈吗?
I'm wondering where I should throw, catch exception in my Zend Framework + Doctrine 2 MVC application.
Here is my design:
Database - MySQL > ORM (Doctrine2) > Service > Controller
My Service take service object in argument and return Service response object for almost all methods.
Service response returns a status, messages and the data which can be whatever you want.
My controllers consumes those services.
I'm wondering where should I throw my exception.
Example:
public function getAllMembers(ServiceObject $data)
{
// do some mapping with $data
$users = $userRepository->getAllMembers($data);
$response = new ServiceResponse('success');
$response->setData($users);
return $response;
}
Should I check for parameters in my Service, and then throw an exception which my controller can catch, or should I throw in, let's say my repository for this example, and catch in my service to allow me to return a ServiceResponse with an error status?
Any feedback about this kind of architecture?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我通常将异常尽可能深入到代码中(在本例中,它将位于存储库内),然后在最合适的地方捕获它们。在这种情况下,我认为最合适的做法是在服务中捕获它,然后返回带有错误状态的 ServiceResponse (否则您只会返回成功消息,这将使 ServiceResponse 变得多余)。
I usually through my exceptions as deep into the code as possible (in this case, it would be inside the repository), and then catch them wherever it would be most appropriate. In this case, I think the most appropriate thing to do would be catch it in the Service and then return a ServiceResponse with an error status (otherwise you'd only be returning success messages, which would make the ServiceResponse kind of redundant).