系列目录

上一节我们讲了如何捕获异常和记录日志,这一节我们讲,没有捕获的或者忘记捕获的异常包括404错误等,我们统一处理这个异常。

这一讲是利用 Application_Error 捕获所有异常,全局的异常处理为了减少代码,统一异常处理,Application_Error位于Global.asax里面,

protected void Application_Error(object sender, EventArgs e)

当一个异常在调用堆栈中没有被处理,也没有被框架代码处理时,我们说这个异常未处理,它将被ASP.NET捕获

它将捕获所有 Application 级别的 UnhandleException 和 HttpException(比如:访问的页面不存在等)

总之,在这里处理的话,那么在页面中的所有 try/catch 处理都可以不要了,但是我们为了记录日志,在BLL层还是要try catch

对此未处理错误的处理方法是显示一个页面,列出该未处理异常的详细情况。

我们通过 Application_Error事件把错误写进对应的文件里面或者数据库中。

 /// <summary>
/// 全局的异常处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Application_Error(object sender, EventArgs e)
{
string s = HttpContext.Current.Request.Url.ToString();
HttpServerUtility server = HttpContext.Current.Server;
if (server.GetLastError() != null)
{
Exception lastError = server.GetLastError();
// 此处进行异常记录,可以记录到数据库或文本,也可以使用其他日志记录组件。
ExceptionHander.WriteException(lastError);
Application["LastError"] = lastError;
int statusCode = HttpContext.Current.Response.StatusCode;
string exceptionOperator = "/SysException/Error";
try
{
if (!String.IsNullOrEmpty(exceptionOperator))
{
exceptionOperator = new System.Web.UI.Control().ResolveUrl(exceptionOperator);
string url = string.Format("{0}?ErrorUrl={1}", exceptionOperator, server.UrlEncode(s));
string script = String.Format("<script language='javascript' type='text/javascript'>window.top.location='{0}';</script>", url);
Response.Write(script);
Response.End();
}
}
catch { }
}
}

嘿嘿,我创造了一个错误 Convert.ToInt16("dddd");下面是错误的显示页面

关于错误页面的制作在控制器SysExceptionController增加

       public ActionResult Error()
{ BaseException ex = new BaseException();
return View(ex);
}

添加BaseException类

 public class BaseException
{
#region 变量
private string exceptionMessage;
private string exceptionName;
private string innerExceptionMessage;
private string innerExceptionName;
private bool isShow;
private Exception outermostException;
private string sourceErrorFile;
private string sourceErrorRowID;
private string stackInfo;
private string targetSite;
#endregion #region 属性
public string ErrorPageUrl
{
get
{
return this.GetExceptionUrl();
}
}
public Exception Exception
{
get
{
return (HttpContext.Current.Session["Exception"] as Exception);
}
private set
{
HttpContext.Current.Session["Exception"] = value;
}
}
public string ExceptionMessage
{
get
{
return this.exceptionMessage;
}
private set
{
this.exceptionMessage = value;
}
}
public string ExceptionName
{
get
{
return this.exceptionName;
}
private set
{
this.exceptionName = value;
}
}
public string InnerExceptionMessage
{
get
{
return this.innerExceptionMessage;
}
private set
{
this.innerExceptionMessage = value;
}
}
public string InnerExceptionName
{
get
{
return this.innerExceptionName;
}
private set
{
this.innerExceptionName = value;
}
}
public bool IsShowStackInfo
{
get
{
return this.isShow;
}
private set
{
this.isShow = value;
}
}
public string SourceErrorFile
{
get
{
return this.sourceErrorFile;
}
private set
{
this.sourceErrorFile = value;
}
}
public string SourceErrorRowID
{
get
{
return this.sourceErrorRowID;
}
private set
{
this.sourceErrorRowID = value;
}
}
public string StackInfo
{
get
{
return this.stackInfo;
}
private set
{
this.stackInfo = value;
}
}
public string TargetSite
{
get
{
return this.targetSite;
}
private set
{
this.targetSite = value;
}
}
#endregion public BaseException()
{
this.outermostException = null;
this.exceptionName = null;
this.exceptionMessage = null;
this.innerExceptionName = null;
this.innerExceptionMessage = null;
this.targetSite = null;
this.stackInfo = null;
this.sourceErrorFile = null;
this.sourceErrorRowID = null;
this.isShow = false;
try
{
this.Exception = HttpContext.Current.Application["LastError"] as Exception;
if (this.Exception != null)
{
this.outermostException = this.Exception;
if ((this.Exception is HttpUnhandledException) && (this.Exception.InnerException != null))
{
this.Exception = this.Exception.InnerException;
}
this.ExceptionName = this.GetExceptionName(this.Exception);
this.ExceptionMessage = this.GetExceptionMessage(this.Exception);
if (this.Exception.InnerException != null)
{
this.InnerExceptionName = this.GetExceptionName(this.Exception.InnerException);
this.InnerExceptionMessage = this.GetExceptionMessage(this.Exception.InnerException);
}
this.TargetSite = this.GetTargetSite(this.Exception);
this.StackInfo = this.GetStackInfo(this.Exception);
if ((this.outermostException is HttpUnhandledException) && (this.outermostException.InnerException != null))
{
this.StackInfo = this.StackInfo + "\r\n<a href='#' onclick=\"if(document.getElementById('phidden').style.display=='none') document.getElementById('phidden').style.display='block'; else document.getElementById('phidden').style.display='none'; return false;\"><b>[" + this.outermostException.GetType().ToString() + "]</b></a>\r\n";
this.StackInfo = this.StackInfo + "<pre id='phidden' style='display:none;'>" + this.outermostException.StackTrace + "</pre>";
}
this.SourceErrorFile = this.GetSourceErrorFile();
this.SourceErrorRowID = this.GetSourceErrorRowID();
this.IsShowStackInfo = true;
}
HttpContext.Current.Session["LastError"] = null;
}
catch (Exception exception)
{
this.ExceptionMessage = "异常基页出错" + exception.Message;
}
} #region 方法
private string GetExceptionMessage(Exception ex)
{
return ex.Message;
} private string GetExceptionMessageForLog()
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("<ExceptionName>{0}</ExceptionName>", this.ExceptionName);
builder.AppendFormat("<ExceptionMessage>{0}</ExceptionMessage>", this.ExceptionMessage);
builder.AppendFormat("<InnerExceptionName>{0}</InnerExceptionName>", this.InnerExceptionName);
builder.AppendFormat("<InnerExceptionMessage>{0}</InnerExceptionMessage>", this.InnerExceptionMessage);
builder.AppendFormat("<TargetSite>{0}</TargetSite>", this.TargetSite);
builder.AppendFormat("<ErrorPageUrl>{0}</ErrorPageUrl>", this.ErrorPageUrl);
builder.AppendFormat("<SourceErrorFile>{0}</SourceErrorFile>", this.SourceErrorFile);
builder.AppendFormat("<SourceErrorRowID>{0}</SourceErrorRowID>", this.SourceErrorRowID);
return builder.ToString();
} private string GetExceptionMessageForMail()
{
StringBuilder builder = new StringBuilder();
builder.Append("<ExceptionInfo>");
builder.Append(this.GetExceptionMessageForLog());
builder.AppendFormat("<StackInfo><![CDATA[{0}]]></StackInfo>", this.StackInfo);
builder.Append("</ExceptionInfo>");
return builder.ToString();
} private string GetExceptionName(Exception ex)
{
string str = null;
if (ex != null)
{
str = ex.GetType().FullName;
} return str;
} private string GetExceptionUrl()
{
string str = null;
if (HttpContext.Current.Request["ErrorUrl"] != null)
{
str = HttpContext.Current.Request["ErrorUrl"].ToString();
}
return str;
} private string GetSourceErrorFile()
{
string stackInfo = this.StackInfo;
string[] strArray = new string[];
if (stackInfo == null)
{
return stackInfo;
}
strArray = stackInfo.Split(new string[] { "位置", "行号" }, StringSplitOptions.RemoveEmptyEntries);
if (strArray.Length >= )
{
stackInfo = strArray[];
if (stackInfo.LastIndexOf(":") == (stackInfo.Length - ))
{
stackInfo = stackInfo.Substring(, stackInfo.Length - );
}
return stackInfo;
}
return "";
}
private string GetSourceErrorRowID()
{
string stackInfo = this.StackInfo;
string[] strArray = new string[];
if (stackInfo == null)
{
return stackInfo;
}
strArray = stackInfo.Split(new string[] { "行号" }, StringSplitOptions.RemoveEmptyEntries);
if (strArray.Length >= )
{
stackInfo = strArray[].Trim();
string[] strArray2 = stackInfo.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
if (strArray2.Length >= )
{
stackInfo = strArray2[];
}
return stackInfo;
}
return "";
}
private string GetStackInfo(Exception ex)
{
string str = null;
if (ex != null)
{
str = "<b>[" + ex.GetType().ToString() + "]</b>\r\n" + ex.StackTrace;
if (ex.InnerException != null)
{
str = this.GetStackInfo(ex.InnerException) + "\r\n" + str;
}
}
return str;
}
private string GetTargetSite(Exception ex)
{
string str = null;
if (ex != null)
{
ex = this.GetBenmostException(ex);
MethodBase targetSite = ex.TargetSite;
if (targetSite != null)
{
str = string.Format("{0}.{1}", targetSite.DeclaringType, targetSite.Name);
}
}
return str;
}
protected Exception GetBenmostException(Exception ex)
{
while (true)
{
if (ex.InnerException != null)
{
ex = ex.InnerException;
}
else
{
return ex;
}
}
}
#endregion
}

BaseException

添加Error视图

@model App.Admin.Controllers.BaseException

@{
ViewBag.Title = "异常处理页面";
Layout = "~/Views/Shared/_Index_Layout.cshtml";
} <h2>系统错误</h2>
<div style="text-align:center;">
<table width="100%" class="blueTab" border="" cellspacing="" cellpadding="">
<tr>
<td colspan="">
<table cellspacing="" cellpadding="" width="100%" border="">
<tbody>
<tr>
<td >
&nbsp;错误处理页面</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr id="youhaotishi" >
<td colspan="" align="left">
&nbsp;欢迎您光临本网站!网站运行发生错误,请与管理员联系。错误原因可能如下:
<br />
&nbsp;&nbsp;&nbsp;.非法访问页面.
<br />
&nbsp;&nbsp;&nbsp;.您输入的数据错误.
<br />
&nbsp;&nbsp;&nbsp;.您访问的页面不存在.
<br />
&nbsp;&nbsp;&nbsp;.内容不存在,或已被删除.
<br />
&nbsp;&nbsp;&nbsp;.系统忙,请稍候再试.
</td>
</tr>
<tbody id="detailInformation" style="display: none;">
<tr>
<td width="20%" class="alignRight" nowrap>
<strong>出错页面:</strong>
</td>
<td class="alignLeft">
@Html.DisplayFor(model => model.ErrorPageUrl) </td>
</tr>
<tr>
<td class="alignRight" nowrap>
<strong>异常名称:</strong>
</td>
<td class="alignLeft">
@Html.DisplayFor(model => model.ExceptionName) </td>
</tr>
<tr>
<td class="alignRight" nowrap>
<strong>异常信息:</strong>
</td>
<td class="alignLeft">
@Html.DisplayFor(model => model.ExceptionMessage) </td>
</tr>
<tr id="trInnerExceptionName" runat="server">
<td class="alignRight" nowrap>
<strong>内部异常名称:</strong>
</td>
<td class="alignLeft">
@Html.DisplayFor(model => model.InnerExceptionName) </td>
</tr>
<tr id="trInnerExceptionMessage" runat="server">
<td class="alignRight" nowrap>
<strong>内部异常信息:</strong>
</td>
<td class="alignLeft">
@Html.DisplayFor(model => model.InnerExceptionMessage)
</td>
</tr>
<tr id="trExceptionMethod" runat="server">
<td class="alignRight" nowrap>
<strong>方法名称:</strong>
</td>
<td class="alignLeft" style="background-color: #ffffcc;">
&nbsp;@Html.DisplayFor(model => model.TargetSite) </td>
</tr>
<tr id="trExceptionSource" runat="server">
<td class="alignRight" nowrap>
<strong>源文件:</strong>
</td>
<td class="alignLeft" style="background-color: #ffffcc;">
@Html.DisplayFor(model => model.SourceErrorFile)
</td>
</tr>
<tr id="trExceptionRowId" runat="server">
<td class="alignRight" nowrap>
<strong>行号:</strong>
</td>
<td class="alignLeft" style="background-color: #ffffcc; color: Red">
&nbsp;@Html.DisplayFor(model => model.SourceErrorRowID) </td>
</tr>
<tr runat="server" id="trStack" visible="false">
<td class="alignRight">
<strong>堆栈跟踪:</strong>
</td>
<td class="alignLeft" style="background-color: #ffffcc;">
<code>
<pre id="litStack"><textarea name="errormsg" cols="" rows="" readonly="readonly">@Html.DisplayFor(model => model.StackInfo) </textarea> </pre>
</code>
</td>
</tr>
</tbody>
</table>
<a id="showMessage" href="#" onclick="ShowErrorMessage();return false;">显示详细信息</a>
</div> <script type="text/javascript"> var isShowMessage = true; function ShowErrorMessage() { var obj = document.getElementById("showMessage")
var detailInformation = document.getElementById("detailInformation");
var youhaotishi = document.getElementById("youhaotishi"); if (isShowMessage) {
obj.innerText = "隐藏详细信息";
isShowMessage = false;
detailInformation.style.display = "block";
youhaotishi.style.display = "none";
}
else {
obj.innerText = "显示详细信息";
isShowMessage = true;
detailInformation.style.display = "none";
youhaotishi.style.display = "block";
} }
</script>

Error.cshtml

由于系统是后台系统,我并没有做得很漂亮的错误页面(实际很丑),大家发货你的想象力和美工能力,造一个好看的,记得共享给我,有奖

构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(13)-系统日志和异常的处理③的更多相关文章

  1. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(1)-前言与目录(持续更新中...)

    转自:http://www.cnblogs.com/ymnets/p/3424309.html 曾几何时我想写一个系列的文章,但是由于工作很忙,一直没有时间更新博客.博客园园龄都1年了,却一直都是空空 ...

  2. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(48)-工作流设计-起草新申请 系列目录 创建新表单之后,我们就可以起草申请了,申请按照严格的表单步骤和分 ...

  3. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(47)-工作流设计-补充 系列目录 补充一下,有人要表单的代码,这个用代码生成器生成表Flow_Form表 ...

  4. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(46)-工作流设计-设计分支 系列目录 步骤设置完毕之后,就要设置好流转了,比如财务申请大于50000元( ...

  5. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(45)-工作流设计-设计步骤 系列目录 步骤设计很重要,特别是规则的选择. 我这里分为几个规则 1.按自行 ...

  6. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(44)-工作流设计-设计表单 系列目录 设计表单是比较复杂的一步,完成一个表单的设计其实很漫长,主要分为四 ...

  7. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(43)-工作流设计-字段分类设计 系列目录 建立好42节的表之后,每个字段英文表示都是有意义的说明.先建立 ...

  8. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(42)-工作流设计01 工作流在实际应用中还是比较广泛,网络中存在很多工作流的图形化插件,可以做到拉拽的工 ...

  9. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-【过滤器+Cache】

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(40)-精准在线人数统计实现-[过滤器+Cache] 系列目录 上次的探讨没有任何结果,我浏览了大量的文章 ...

  10. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构

    原文:构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(41)-组织架构 本节开始我们要实现工作流,此工作流可以和之前的所有章节脱离关系,也可以紧密合并. 我们当 ...

随机推荐

  1. 恢复SQL Server被误删除的数据(再扩展)

    恢复SQL Server被误删除的数据(再扩展) 大家对本人之前的文章<恢复SQL Server被误删除的数据> 反应非常热烈,但是文章里的存储过程不能实现对备份出来的日志备份里所删数据的 ...

  2. MVVM设计模式和WPF中的实现(四)事件绑定

    MVVM设计模式和在WPF中的实现(四) 事件绑定 系列目录: MVVM模式解析和在WPF中的实现(一)MVVM模式简介 MVVM模式解析和在WPF中的实现(二)数据绑定 MVVM模式解析和在WPF中 ...

  3. C#中如何调整图像大小

    在本篇文章中,我将介绍如何在C#中来调整你想要的图像大小.要实现这一目标,我们可以采取以下几个步骤: 1.首先要获取你想要调整大小的图像: string path = Server.MapPath(& ...

  4. SQL Server2016升级前几点自检

    SQL Server2016已经出来一段时间了,而且最新的SP1包也于2016年11月18日正式发布,各种新的特性推出让我们跃跃欲试.那么对于我们真实的业务环境,特别是生产环境要不要"跟风& ...

  5. Spark踩坑记——初试

    [TOC] Spark简介 整体认识 Apache Spark是一个围绕速度.易用性和复杂分析构建的大数据处理框架.最初在2009年由加州大学伯克利分校的AMPLab开发,并于2010年成为Apach ...

  6. C# 对象实例化 用json保存 泛型类 可以很方便的保存程序设置

    用于永久化对象,什么程序都行,依赖NewtonSoft.用于json序列化和反序列化. using Newtonsoft.Json; using System; using System.Collec ...

  7. 防线修建 bzoj 2300

    防线修建(1s 512MB)defense [问题描述] 近来A国和B国的矛盾激化,为了预防不测,A国准备修建一条长长的防线,当然修建防线的话,肯定要把需要保护的城市修在防线内部了.可是A国上层现在还 ...

  8. 每天一个设计模式-7 生成器模式(Builder)

    每天一个设计模式-7 生成器模式(Builder) 一.实际问题 在讨论工厂方法模式的时候,提到了一个导出数据的应用框架,但是并没有涉及到导出数据的具体实现,这次通过生成器模式来简单实现导出成文本,X ...

  9. 【干货分享】流程DEMO-补打卡

    流程名: 补打卡申请 业务描述: 当员工在该出勤的工作日出勤但漏打卡时,于一周内填写补打卡申请. 流程相关文件: 流程包.xml 流程说明: 直接导入流程包文件,即可使用本流程 表单:  流程: 图片 ...

  10. 报错:You need to use a Theme.AppCompat theme (or descendant) with this activity.

    学习 Activity 生命周期时希望通过 Dialog 主题测试 onPause() 和 onStop() 的区别,点击按钮跳转 Activity 时报错: E/AndroidRuntime: FA ...