一个关于C#错误处理的问题

由于以前的项目没有重视错误返回,基本上所有的try catch块里面都没有抛出异常代码,也就是catch只是捕捉到错误而没有让这个错误返回到界面上,我现在的想法是建一个类,只要catch捕捉到了异常,就会把异常日志写到这个类里面(我想由程序自动处理,而不是再到每个catch里面去加代码,那工作量太大了),然后在界面层将这个类的异常显示出来

慕勒3428872
浏览 449回答 2
2回答

明月笑刀无情

在全局文件 Global.asax 中做处理。截获出现异常时的事件,并自定义处理过程。参考下面代码,增加一个日志的写入就ok了。void Application_Error(object sender, EventArgs e)    {        //在出现未处理的错误时运行的代码        HttpContext context = ((HttpApplication)sender).Context;        Exception ex = context.Server.GetLastError();        if (ex == null || !(ex is HttpException) || (ex as HttpException).GetHttpCode() == 404)            return;        StringBuilder sb = new StringBuilder();        try        {            sb.Append("Url : " + context.Request.Url);            sb.Append(Environment.NewLine);            sb.Append(" Raw Url :" + context.Request.RawUrl);            sb.Append(Environment.NewLine);            while (ex != null)            {                sb.Append("Message : " + ex.Message);                sb.Append(Environment.NewLine);                sb.Append("Source : " + ex.Source);                sb.Append(Environment.NewLine);                sb.Append("StackTrace : " + ex.StackTrace);                sb.Append(Environment.NewLine);                sb.Append("TagetSite : " + ex.TargetSite);                sb.Append(Environment.NewLine);                ex = ex.InnerException;            }        }        catch (Exception ex2)        {            sb.Append("Error logging error : " + ex2.Message);        }        if (OASettings.Instance.EnableErrorLogging)            Utils.Log(sb.ToString());        context.Items["LastErrorDetails"] = sb.ToString();        context.Response.StatusCode = 500;        Server.ClearError();        context.Server.Transfer("~/error.aspx");    }

30秒到达战场

你可以看看我的这篇文章:使用log4net完成程序异常日志记录(使用SQLite数据库记录和普通文本记录)然后根据你的需求进行些处理。可以写个程序在记录了异常后实时提醒。
打开App,查看更多内容
随时随地看视频慕课网APP