在我们的项目中,我们一般只会捕获我们自己能够想到的异常,但是这样就会导致一些无法捕捉到的异常被漏出去,因为我们不能确定它们会在什么地方出现,例如像NullPointerException,ClassCastException,IndexOutOfBoundsException这些RuntimeException,我们可以在所有它们有可能发生的地方去捕获它们,但这确实是很坏的解决方案。但是又不能不处理,把程序的错误页面、核心代码暴露给用户是非常不好的做法!
我们可以在web.config文件中通过增加配置文件来统一捕获异常。 我们只需要在
<system.web></system.web>
中增加一个节点
<customErrors mode="On" defaultRedirect="CustomerErrorPage.aspx" />
就可以捕获到客户端所有的异常。

关于这个mode,有三个值
on :如果有未捕捉的异常,就直接调到错误页面,一般用在项目、产品发布以后。
off: 用户可以看到所谓的黄页,而不是跳转到错误页面,用在项目开发中。
remoteonly:本机运行的用户可以看到错误页面,而远端的任何用户都是调到错误页面。
捕获到异常以后我们可以异常放到文档,或者写入数据库, 捕获到的异常如下:
Exception lastException = HttpContext.Current.Server.GetLastError().InnerException;
一般来说我们如果需要对404做单独的处理可以采用如下的代码:
 1public 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
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}
posted on 2007-12-06 10:18  叶飞  阅读(1153)  评论(0编辑  收藏  举报