服务层Dao异常处理 [英] Handling Dao exceptions in service layer

查看:33
本文介绍了服务层Dao异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的 Dao 层抛出 Dao 特定的异常,那么在我的服务层中处理它们是否构成了关注点泄漏?如果是,那么我应该使异常通用且独立于任何层来解决它,还是有其他方法?

If my Dao layer throws Dao specific exceptions, then does handling them in my service layer consitute a leakage of concerns? If yes, then should I make the exceptions generic and independent of any layer to address it, or is there some other way?

同样的问题也适用于 UI 层处理服务层抛出的异常.

The same question is applicable to UI layer handling exceptions thrown by service layer.

推荐答案

当我们创建一个分层的应用程序时,总会有一个用户层和另一个使用层.对于这种情况,UI 层 -> 使用服务层 -> 使用 DAO 层.

When we create a layered application, there is always a user layer and another used layer. For this case UI layer -> uses service Layer -> uses DAO layer.

现在它非常主观且易于解释.但目标应该是良好程度的解耦.为了实现这一点,一种方法是定义通用的层特定异常,比如PersistentExceptionServiceException等.这些异常将包装实际的层特定异常.

Now its very subjective and open to interpretations. But the objective should be a good degree of decoupling. To achieve this, one way out is the define generic layer specific exceptions say PersistentException, ServiceException etc. These exception will wrap the actual layer specific exception.

例如说如果数据库端有一些错误(违反约束等),把它包装在 PersistentException 中,让服务层处理它(关于如何将它传达给 UI 层在一个通用的方式)

For example say if there is some error on database side (Constraint violation etc), wrap that in PersistentException and let service layer handle that (as to how to convey this to UI layer in a generic way)

现在由于服务层和 DAO 层之间的集成契约(基于接口),DAO层可以自由地将实现更改为任何东西,只要它遵守接口契约.因此,如果您更改抛出一些新异常的实现,这些新异常可以包装在 PersistentException 中,并且 Service 层不受影响.

Now since the integration between service layer and DAO layer is contractual (interface based), the DAO layer is free to change the implementation to anything as long as it obeys the interface contract. So if you change the implementation which throws some new exceptions, those new exceptions can be wrapped in PersistentException and Service layer remains unaffected.

这篇关于服务层Dao异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆