关于在WEB这方面对异常的处理,这里用的用的开发模式为MVC。最近在学习Wed编程,这里开始正真的接触异常,算然以前在CoreJaca那里接触过异常,但是那个时间学习的异常只是一个HelloWord,学一段Web课程以后,异常在项目里是必须要处理的,这里也认识异常处理的重要性。
在处理主要包括以下几步:
一、异常的预处理
1、先自定义一个异常
2、定义异常发生以后要转发页面、
二、在持久层这里捕获异常, 这里包括(Dao、Hibernate)当在捕获异常时事务回滚,抛出自定义异常
具体的代码:
public class SomeDao {
public void insert() {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
try {
if (true)
throw new HibernateException("error!!!");
tx.commit();
} catch (HibernateException e) {
tx.rollback();
throw new DaoException("insert error", e);
} finally {
HibernateSessionFactory.closeSession();
}
}
}
三、在控制层这里又分为其他的模块:
1、Action先抛出异常(这里抛出DaoException)具体代码:
public class OneAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return mapping.findForward("success");
}
}
2、Struts.xml里调用<exception key="exception.dao" type="exception.DaoException" path="/WEB-INF/jsp/error.jsp" />信息,更具这里的信息转发到相应的页面