当网站发生异常了怎么办呢?难道我们需要一直去翻阅Tomcat的日志文件吗?
本代码是oschina用来将所有的500错误的信息发送给指定的邮箱
1. [代码]500.vm
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>应用程序出错</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="$link.css("osc-error.css")" type="text/css" media="screen" />
</head>
<body>
#set($__nothing = $osc_tool.report_error($request))
<div id='msg-box'>
<div class='logo'><a href="$link.root()"><img src="$link.img('logo.gif')" border="0" alt=""></a></div>
<div class='title'>您访问的页面发生错误!</div>
<div class='msg'>我们已经将此错误信息记录下来,并将尽快处理,为此造成您的不便请多见谅</div>
<div class='nav'><a href="$link.root()">> 返回首页 <</a></div>
</div>
</body>
</html>2. [代码]web.xml
<error-page>
<error-code>500</error-code>
<location>/500.vm</location>
</error-page>3. [代码][Java]代码
/**
* 报告错误信息
* 在vm上的用法 $osc_tool.report_error($request)
* @param t
*/
public static void report_error(HttpServletRequest req){
SmtpHelper.reportError(req, null);
}4. [代码]SmtpHelper.java
/**
* 报告错误信息
* @param req
* @param excp
*/
public static void reportError(HttpServletRequest req, Throwable excp){
boolean is_localhost = (req!=null)?"127.0.0.1".equals(RequestUtils.getRemoteAddr(req)):false;
Throwable t = excp;
if(t == null) t = _GetException(req);
if(t == null) return ;
log.error("System Exception", t);
if(!is_localhost)
//发送电子邮件通知
try {
String email = smtp_props.getProperty("administrator");
String title = ResourceUtils.getString("ui", "error_500", t.getClass().getSimpleName());
String content = getErrorHtml(req, t);
//发送邮件到指定邮箱
_SendHtmlMail(Arrays.asList(StringUtils.split(email,",")), title, content);
} catch (Exception e) {
log.error("Failed to send error report.", e);
}
}