gpt4 book ai didi

c# - 以最佳方式捕获站点上的所有异常

转载 作者:行者123 更新时间:2023-11-30 15:36:51 25 4
gpt4 key购买 nike

我正在尝试找出一种方法来捕获网站上的所有异常并存储它们,但问题是我不想去 try catch 所有内容。

我已经找到了自定义错误页面的解决方案并且我正在这样做,但我希望作为管理员知道用户何时遇到错误,以及错误是什么。而且我知道必须有一种方法可以全局获取所有异常并存储它们。

几天来我一直在寻找解决方案或至少是指向正确方法的东西,但我发现的只是笨拙的方法。

所以我的问题是。有这样的一站式服务吗?我可以捕获异常并在一个地方执行存储过程而不向我的解决方案中的每个类添加一些东西吗?在那种情况下,我应该在哪里运行我的存储过程?

最佳答案

将 Global.asax 文件添加到您的 asp.net 项目并处理应用程序错误:

    void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
string errorMessage = "Application Exception: " + ex.Message;
if (ex.InnerException != null)
{
errorMessage += Environment.NewLine + "Inner Exception: " + ex.InnerException.Message;
}
if (Context != null && Context.Request != null)
{
errorMessage += Environment.NewLine + "Absolute Url: " + Context.Request.Url.AbsolutePath;
}
Services.LoggerManager.Log(
Services.LoggerManager.eLogContext.Application,
Services.LoggerManager.eLogType.Error,
Context, errorMessage);
}

这是 LoggerManager 部分:

public static class LoggerManager
{

public enum eLogType
{
Information = 0,
Warning = 1,
Error = 2
}

public enum eLogContext
{
Application = 0,
Session = 1
}

/// <summary>
/// Method for logging custom message
/// </summary>
/// <param name="logContext"></param>
/// <param name="logType"></param>
/// <param name="context"></param>
/// <param name="message"></param>
public static void Log(eLogContext logContext, eLogType logType, HttpContext context, string message)
{
switch (logContext)
{
case eLogContext.Application:
//TODO: log application type event...
break;
case eLogContext.Session:
//TODO: log session type event...
break;
default:
throw new NotImplementedException("eLogContext '" + logContext.ToString() + "' is not implemented!");
}
}

}

关于c# - 以最佳方式捕获站点上的所有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13331270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com