多层结构中那么底层出错的时候应该往上抛出异常,否则如果你只打印一些堆栈用户是不会知道的.这关涉到了异常处理.
异常处理有手动处理的异常(编程式异常)和自动的异常处理(声明式异常),手动处理的异常就是自己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");
}
%>