我发现很难在Stackoverflow的现有答案中找到我的查询的答案,这就是我决定提出问题的原因。
我想用Try Catch处理错误,但e.Message的默认信息不是我需要的。
基本上在使用断点时,我可以看到Exception对象在挖掘时有可用的数据。
PositionMessage类型是字符串,因此我想使用此数据来提供Catch行为。我无法弄清楚如何将这个特定字段的值分配给变量。
我希望你能帮助我。
答案 0 :(得分:3)
异常可以是System.Management.Automation.RuntimeException类型,在这种情况下它实现IContainsErrorRecord
。这意味着它具有ErrorRecord属性(您正在寻找的)。您可以尝试强制转换它,如果成功,您可以访问PositionMessage。否则(它不是RuntimeException),然后将其视为正常的异常。
Sub Main()
Try
' do stuff
Catch ex As Exception
Dim e = TryCast(ex, IContainsErrorRecord)
Dim message As String
If e IsNot Nothing Then
message = e.ErrorRecord.InvocationInfo.PositionMessage
Else
message = ex.Message
End If
Console.WriteLine(message)
End Try
End Sub
答案 1 :(得分:1)
NB: This is C#, but trivial to convert to VB. I do something like this:
results = pipeline.Invoke();
if (pipeline.Error.Count > 0)
{
var errors = pipeline.Error.Read() as Collection<ErrorRecord>;
if (errors != null)
{
foreach (ErrorRecord err in errors)
{
Console.WriteLine(err.InvocationMessage.PositionMessage);
}
}
}