使用反射或通过 HttpContext.Current.Server.GetLastError() 捕获最后一个异常

发布于 2025-01-03 06:49:46 字数 372 浏览 2 评论 0原文

我有一个在引发异常时调用的方法。仅将 Exception.ToString() 传递给它。目前不可能更改参数以接受 Exception 而不是字符串,因为我们必须更改很多页面,而我对此无法控制(请不要这样做)需要有人告诉我这样做,因为相信我,我很乐意这样做)。我们已经有一个处理异常的类,但我有机会更新此方法,并且我想知道是否可以使用反射或使用 HttpContext.Current.Server.GetLastError()< 来获取最后一个异常/代码>。使用GetLastError()它不起作用,因为异常已被处理。有没有办法通过反思或其他方式解决这个问题?非常感谢任何帮助。如果之前讨论过这个问题,请告诉我,因为我找不到类似的问题。

I have a method that is called when an exception is thrown. Only the Exception.ToString() is passed to it. It is not possible at this time to change the parameters to accept an Exception instead of a string, because we would have to change a lot of pages and I have no control over that (please I don't need anyone telling me to do that, because trust me I would love to just do that). We already have a class that handles the exceptions, but I have the opportunity to update this method and I wanted to know if it was possible to grab the last exception using reflection or using HttpContext.Current.Server.GetLastError(). With the GetLastError() it does not work because the exception was handled. Is there a way around this maybe with reflection or something? Any help is greatly appreciated. If this was discussed before, please show me because I was unable to find a similar question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷默言语 2025-01-10 06:49:46

我现在使用的快速解决方案(使用异常和反射中的一些信息):

 string typeName = err.Substring(0, err.IndexOf(":"));
 string message = err.Length > typeName.Length + 2 ? err.Substring(err.IndexOf(":") + 1) : string.Empty;
 Type type = Type.GetType(typeName);
 ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
 object exception = ctor.Invoke(new object[] { message });

string err 是异常.ToString(),它将具有异常类型,然后我将消息作为 tostring 方法的其余部分。这实际上会做。如果我想非常明确,我可以使用反射来编辑每个属性,但是那里有出错的空间,并且 tostring 实际上将拥有一切,并且由于我正在创建异常类型,因此在引擎盖中一切都很好。 :) 希望这对某人有帮助

Quick fast solution I used for now (using some info from Exception and Reflection):

 string typeName = err.Substring(0, err.IndexOf(":"));
 string message = err.Length > typeName.Length + 2 ? err.Substring(err.IndexOf(":") + 1) : string.Empty;
 Type type = Type.GetType(typeName);
 ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string) });
 object exception = ctor.Invoke(new object[] { message });

string err is the Exception.ToString(), which will have the type of exception and then I make the message the rest of the tostring method. This will do actually. If I wanted to be really explicit I could have used reflection to edit each property, but there is room for error there and the tostring actually will have everything and since I am creating the exception type it's all good in the hood. :) Hope this helps someone

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文