在捕获块中,如何获得抛出异常的行号?
当前回答
在全球。resx文件中有一个名为Application_Error的事件
每当发生错误时,它就会触发,您可以很容易地获得有关错误的任何信息,并将其发送到错误跟踪电子邮件。
此外,我认为所有你需要做的是编译全局。Resx并将其dll's (2 dll)添加到您的bin文件夹,它将工作!
其他回答
如果你没有。pbo文件:
C#
public int GetLineNumber(Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
Vb.net
Public Function GetLineNumber(ByVal ex As Exception)
Dim lineNumber As Int32 = 0
Const lineSearch As String = ":line "
Dim index = ex.StackTrace.LastIndexOf(lineSearch)
If index <> -1 Then
Dim lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length)
If Int32.TryParse(lineNumberText, lineNumber) Then
End If
End If
Return lineNumber
End Function
或者作为Exception类的扩展
public static class MyExtensions
{
public static int LineNumber(this Exception ex)
{
var lineNumber = 0;
const string lineSearch = ":line ";
var index = ex.StackTrace.LastIndexOf(lineSearch);
if (index != -1)
{
var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
if (int.TryParse(lineNumberText, out lineNumber))
{
}
}
return lineNumber;
}
}
Convert.ToInt32(ex.StackTrace.Substring(ex.StackTrace.LastIndexOf(' ')));
这将给出异常行no。
如果生成异常的库是用调试符号编译的,那么行号将包含在堆栈跟踪中。这可以是一个单独的文件(*.pdb),也可以嵌入到库中。
对于.NET Core、.NET 5及更高版本,要在发布版本中拥有完整的异常行号,请按如下方式配置项目:
<PropertyGroup>
<DebugSymbols>true</DebugSymbols>
<DebugType>embedded</DebugType>
<!-- Only enable the following if the line numbers mismatch -->
<!--<Optimize>false</Optimize>-->
<!--
Additional properties which may impact how printed line numbers match the source code line numbers are listed here:
https://learn.microsoft.com/en-us/dotnet/core/run-time-config/compilation
-->
</PropertyGroup>
上面的配置将在构建的文件中直接包含调试符号,这些符号可以作为块发布。
上面的替代方法是将调试包与主要的nuget包一起恢复,目前还不支持:https://github.com/NuGet/Home/issues/9667
现在获取异常行号:
try
{
throw new Exception();
}
catch (Exception ex)
{
// Get stack trace for the exception with source file information
var st = new StackTrace(ex, true);
// Get the top stack frame
var frame = st.GetFrame(0);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
}
如果你的堆栈跟踪大于1,它应该是:
var st = new StackTrace(es, true);
// Get the top stack frame
var frame = st.GetFrame(st.FrameCount - 1);
//从栈帧中获取行号 var line = frame.GetFileLineNumber();
在全球。resx文件中有一个名为Application_Error的事件
每当发生错误时,它就会触发,您可以很容易地获得有关错误的任何信息,并将其发送到错误跟踪电子邮件。
此外,我认为所有你需要做的是编译全局。Resx并将其dll's (2 dll)添加到您的bin文件夹,它将工作!
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和