1.
将异常转换为非强制捕获型异常
2.
将异常向上层抛出,并统一处理
3.
在错误页面给出客户友好提示,并通知管理员处理异常信息
- web.xml 错误页配置 (两种)
<!--配置错页-->
<error-page>
<error-code>500</error-code>
<location>/Error.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/ErrorMsg.jsp</location>
</error-page>
- 异常java文件
package com.hisoft.Exception;
public class DataAccessException extends RuntimeException{
public DataAccessException(){}
public DataAccessException(String msg){
super(msg);
}
public DataAccessException(Throwable th){
super(th);
}
public DataAccessException(Throwable th,String msg){
super(msg,th);
}
}
- try catch 处理异常信息(修改错误信息,友好提示)
try {
PreparedStatement ps = conn.prepareStatement("select * from news_users where uname = ?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
newsUser = null;
if(rs.next()){
int uid = rs.getInt("uid");
String upwd = rs.getString("upwd");
newsUser = new NewsUser(uid,uname,upwd);
}
dbUtil.close(rs,ps,conn);
} catch (SQLException sqlException) {
throw new DataAccessException(sqlException,"服务器正在升级中,请稍后重试!");
}
- 错误页:Error.jsp
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" language="java" %>
<body>
<%
Throwable th = null;
if(request.getAttribute("javax.servlet.error.exception") != null){
th = (Throwable)request.getAttribute("javax.servlet.error.exception");
}
if(th != null){
out.println(request.getAttribute("javax.servlet.error.request_uri"));//资源路径
out.println(request.getAttribute("javax.servlet.error.servlet_name"));//servlet名字
out.println(th);
out.print(th.getMessage());//输出错误信息
}
%>
</body>
- 错误页:ErrorMsg.jsp (只有提示)
<body>
<h1>服务器正在升级中,请稍后重试!</h1>
</body>
- 关于错误页的类型:
•
javax.servlet.error.status_code: Integer HTTP
协议的状态代码
•
javax.servlet.error.exception_type: Class
未捕获异常的
Class
类的对象
•
javax.servlet.error.message: String
传递给
sendError()
方法的消息
•
javax.servlet.error.exception: Throwable
调用错误页面的未捕获异常
•
javax.servlet.error.request_uri: String
当前请求的
URI
•
javax.servlet.error.servlet_name: String
导致错误页面被调用的
Servlet
的名字