我们可以在web.config文件中通过增加配置文件来统一捕获异常。 我们只需要在
<system.web></system.web>
中增加一个节点
<customErrors mode="On" defaultRedirect="CustomerErrorPage.aspx" />
就可以捕获到客户端所有的异常。
关于这个mode,有三个值
on :如果有未捕捉的异常,就直接调到错误页面,一般用在项目、产品发布以后。
off: 用户可以看到所谓的黄页,而不是跳转到错误页面,用在项目开发中。
remoteonly:本机运行的用户可以看到错误页面,而远端的任何用户都是调到错误页面。
捕获到异常以后我们可以异常放到文档,或者写入数据库, 捕获到的异常如下:
Exception lastException = HttpContext.Current.Server.GetLastError().InnerException;
一般来说我们如果需要对404做单独的处理可以采用如下的代码:
1
public
class
Global : HttpApplication
2
{
3
protected void Application_Error(Object sender, EventArgs args)
4
{
5
Exception lastException
=
HttpContext.Current.Server.GetLastError().InnerException;
6
int httpCode
=
0;
7
if
(HttpContext.Current.Server.GetLastError().GetType()
==
typeof(HttpException))
8
{
9
httpCode
=
((HttpException)HttpContext.Current.Server.GetLastError()).GetHttpCode();
10
}
11![](/Images/OutliningIndicators/None.gif)
12
//
If this
is
just a
404
then just redirect to the custom
404
page.
13
if
((exception.InnerException
!=
null
&&
exception.InnerException.GetType()
==
typeof(FileNotFoundException))
||
(exception.GetType()
==
typeof(FileNotFoundException))
||
httpCode
==
404
)
14
{
15
Server.Transfer(
"
/404.htm
"
);
16
return
;
17
}
18
}
19
}
![](/Images/OutliningIndicators/None.gif)
2
![](/Images/OutliningIndicators/None.gif)
3
![](/Images/OutliningIndicators/None.gif)
4
![](/Images/OutliningIndicators/None.gif)
5
![](/Images/OutliningIndicators/None.gif)
6
![](/Images/OutliningIndicators/None.gif)
7
![](/Images/OutliningIndicators/None.gif)
8
![](/Images/OutliningIndicators/None.gif)
9
![](/Images/OutliningIndicators/None.gif)
10
![](/Images/OutliningIndicators/None.gif)
11
![](/Images/OutliningIndicators/None.gif)
12
![](/Images/OutliningIndicators/None.gif)
13
![](/Images/OutliningIndicators/None.gif)
14
![](/Images/OutliningIndicators/None.gif)
15
![](/Images/OutliningIndicators/None.gif)
16
![](/Images/OutliningIndicators/None.gif)
17
![](/Images/OutliningIndicators/None.gif)
18
![](/Images/OutliningIndicators/None.gif)
19
![](/Images/OutliningIndicators/None.gif)