异常处理

 多层结构中那么底层出错的时候应该往上抛出异常,否则如果你只打印一些堆栈用户是不会知道的.这关涉到了异常处理.

异常处理有手动处理的异常(编程式异常)和自动的异常处理(声明式异常),手动处理的异常就是自己try catch掉,在这之中进行处理

声明式异常的配置方式,参见 web.xml配置文件中的<error-page>标签。

通用错误处理页面的声明方式,注意此页中必须加入:<%@ page isErrorPage="true" %>,加入isErrorPage=”true”才可以使用 jsp隐含对象exception

 

异常的几种处理方式
a)  根据每种业务语义创建不同的异常,如:UserNotFoundException,…
b)  每层抛出相应的异常,如:DaoException,SerivceException,…..
c)  每个模块抛出一种异常,如:SysMgrException,…..
d)  只抛出一种异常,如:AppException
e)  错误码可以做到异常细粒度划分,采用错误码可以减少异常类的建立
i.  参见:java.sql.SQLException

例子,在添加item的时候:

public void addItem(Connection conn, Item item) {
  String sql = "insert into t_items (item_no, item_name, spec, pattern, item_category_id, item_unit_id) ";
   sql+=" values (?, ?, ?, ?, ?, ?)";
  PreparedStatement pstmt = null;
  try {
   //Dao的设计粒度一般是细粒度的,如果没有特殊需求,Dao和Manager粒度可以一样,不同考虑太多
   //Dao的设计是比较单纯的,不应该放入过多的业务逻辑(业务规则)
   //如果放置了业务逻辑,有些Manager不采用此业务逻辑,这样这个Dao方法就没有复用率了
   //对于我们的应用来说Dao最底层的,所以应该越通用越好
//   if (findItemById(conn, item.getItemNo()) != null) {
//    throw new ApplicationException("物料代码已经存在,代码=" + item.getItemNo()  + "");
//   }
   pstmt = conn.prepareStatement(sql);
   pstmt.setString(1, item.getItemNo());
   pstmt.setString(2, item.getItemName());
   pstmt.setString(3, item.getSpec());
   pstmt.setString(4, item.getPattern());
   pstmt.setString(5, item.getItemCategory().getId());
   pstmt.setString(6, item.getItemUnit().getId());
   pstmt.executeUpdate();
  }catch(SQLException e) {
   e.printStackTrace();
   //System.out.println("errorCode=" + e.getErrorCode());
   //System.out.println("description=" + e.getMessage());
//   if (e.getErrorCode() == 1) {//具体码值是什么可以去查看Jdk帮助文档
//    throw new ApplicationException("物料代码已经存在,代码【" + item.getItemNo()  + "】");
//   }
   throw new ApplicationException("添加物料失败!");
  }finally {
   DbUtil.close(pstmt);
  }
 }

400,500错误的处理方法:

<error-page>
   <error-code>404</error-code>
   <location>/http_error.jsp</location>
  </error-page>
 
  <error-page>
   <error-code>500</error-code>
   <location>/http_error.jsp</location>
  </error-page>

在处理这样的问题的时候IE有bug,那么要建立一个中间的页面来进行跳转,中间页面

 <error-page>
  <error-code>404</error-code>
  <location>/http_error.jsp</location>
</error-page>
<error-page>
  <error-code>500</error-code>
  <location>/http_error.jsp</location>
</error-page>

中间页面http_error.jsp的内容如下:

<%
  Integer errorCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
  if (errorCode == 404) {
   response.sendRedirect(request.getContextPath() + "/404.jsp");
  }else if (errorCode == 500) {
   response.sendRedirect(request.getContextPath() + "/500.jsp");
  }
 %>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yjsuge

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值