客户端异常的处理

   在我们的项目中,我们一般只会捕获我们自己能够想到的异常,但是这样就会导致一些无法捕捉到的异常被漏出去,因为我们不能确定它们会在什么地方出现,例如像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做单独的处理可以采用如下的代码:
 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
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 }

转载于:https://www.cnblogs.com/imyefei/archive/2007/12/06/984818.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值