java - SSM中异常怎么处理,包括io,net,业务异常???
PHP中文网
PHP中文网 2017-04-18 09:23:49
0
4
835

最近开发的项目中,dao,service,controller中的类都是throws Excepiton,但在方法中为什么还要catch后再抛,想知道SSM开发web应用详细的异常处理机制

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(4)
刘奇

The following is only my personal practice and is for reference only.

When

Controller层:
在没有AOPFilter intervenes, I personally think that all exceptions generated within the methods here must be handled;

DAO层:
这一层的异常多为SQL异常,一般抛给ServiceLayer processing;

ServiceLayer:
If it is considered that the exception does not require the caller's intervention, it will be handled within the Service, otherwise it will be thrown to the caller for processing (actually, it is a scapegoat...);

Only in one case, I will catch and then throw a Exception,就是catch了A异常,然后抛出了B异常,这通常跟使用AOP统一处理异常搭配,例如:catch了A,B,C异常,统一交给AOPD exception handler.

Peter_Zhu

Personally, I think the principle of catching exceptions is that you only need to catch exceptions when the code has business processing needs for the expected exceptions. For example, when a SQL error occurs, you need to roll back the transaction. Otherwise, there is basically no need to catch exceptions, so that the outermost business can Just handle exceptions in a unified manner.

大家讲道理

A few personal suggestions:

(1) Checked exception is converted to RuntimeException,抛这个一般认为是bug
(2)自定义异常(业务异常)继承自RuntimeException,设计自定义异常的时候要考虑异常抛出的时候能够通过日志信息快速重现发生异常的场景。
(3)关于是否抛出异常,一般来说如果需要调用方知晓可能会发生业务异常,并能处理的,就抛。如果调用方无法处理的异常,就catch掉。简而言之就是不要“甩锅”。
(4)强烈不建议catch Exception. This kind of code makes it difficult to quickly locate the problem when an exception occurs.

Ty80

It is recommended that the Dao层,直接往上抛异常(一般都是数据库的运行时异常),Service layer is exposed to other applications, and there will be a lot of business information that needs to be passed to the upper layer callers, so there are two ways here

  1. Inform the caller of specific business exception information/system exception information by throwing business exceptions (system exceptions, the upper layer may not pay attention)

  2. Service中保证不会出现异常,并且返回一个Result给上层,ResultThe information included is: whether the call was successful, and if it failed, there will be some business information

So there is no need to catch exceptions at all levels. If you want to handle it, just handle it in Service (whether it is a single application or a future service). Which of the above methods is used in the service depends on the team's choice

The general business process should be controlled by try{}catch{} or if()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template