• asp.net中 统一处理错误


    转载:

    asp.net中当服务器出错时显示指定的错误页面同时把错误信息写入系统日志文档

    一,在web.config中填写出错时显示的页面,能够根据不同的statuscode显示不同的出错页面。
       <customerrors mode="on"  //假如配置为off则出错只返回错误信息,不会跳到自己的指定页面defaultredirect="/error/customerrorpage.aspx">
        <error statuscode="404" redirect="/error/404page.aspx"/>
        <error statuscode="403" redirect="/error/403page.aspx"/>
      </customerrors>

    二,在global.asax文档中添加应用出错代码,写入系统日志文档
    protected void application_error(object sender, eventargs e)
            {
                exception lasterror = server.getlasterror();
                string errmessage = lasterror.tostring();

                string logname  = "mylog";
                string message = "url " + request.path + " error: " + errmessage;

                // create event log if it doesnt exist
            
                if (!eventlog.sourceexists(logname))
                {
                    eventlog.createeventsource(logname, logname);
                }
                eventlog log = new eventlog();
                log.source  = logname;
                //these are the five options that will display a different icon.
                log.writeentry(message, eventlogentrytype.information, 1);
                log.writeentry(message, eventlogentrytype.error, 2);
                log.writeentry(message, eventlogentrytype.warning, 3);
                log.writeentry(message, eventlogentrytype.successaudit, 4);
                log.writeentry(message, eventlogentrytype.failureaudit, 5);

            }
    三,现在您能够进行测试了。
    我在default.aspx.cs中产生一个错误,果然跳到默认的错误页面!
    private void page_load(object sender, system.eventargs e)
            {
                // put user code to initialize the page here
                try
                {
                    int y=0;
                    int x=1/y;
                }
                catch (exception err)
                {
                    throw new exception("404");//我想产生不同的错误,对应web.config中的statuscode,该如何实现?
                    //err.
                }

    同理:如果要在所有入口处判断SESSION是否过期,例如登录信息,也可以通过 application的全局实践来进行监控

    Application事件的执行顺序-.NET教程,Asp.Net研发
    执行application_beginrequest
    执行application_authenticaterequest
    执行application_authorizerequest
    执行application_resolverequestcache
    执行application_acquirerequeststate
    执行application_prerequesthandlerexecute
    执行application_postrequesthandlerexecute
    执行application_releaserequeststate
    执行application_updaterequestcache
    执行application_endrequest

    类似与JAVA中的拦截器Filter,见前期的文章【使用filter拦截器判断会话是否丢失

  • 相关阅读:
    单例模式
    SRM147 DIV2 950
    SRM147 DIV2 600
    SRM147 DIV2 250
    SRM147 DIV1 1000
    Python 实现字符串反转的9种方法
    ubtuntu redis 集群部署/搭建(官方原始方案)
    Python2 ValueError: chr() arg not in range(256) 解决办法?
    python 字典操作中has_key() 和 in 那个使用更加pythonic?
    Python库 使用filetype精确判断文件类型
  • 原文地址:https://www.cnblogs.com/willpower/p/1258823.html
Copyright © 2020-2023  润新知