scharette
scharette

Reputation: 9997

Catch last inner exception when using the -ErrorAction Stop flag

Here is the code:

Try{
    $connection = Test-Connection -BufferSize 32 -Count 1 -ErrorAction Stop -ComputerName "test"
    return $connection.StatusCode.ToString()
}
Catch [System.Net.NetworkInformation.PingException]{
    return "Ping Exception"
}
Catch [Exception]{
    return "Unexpected exception"
}

Now, let's consider the case where the -ComputerName would not be found, this would return me a System.Net.NetworkInformation.PingException. But, in the above code the output would be Unexpected exception.

Refering to this answer, I should use System.Management.Automation.ActionPreferenceStopException to catch it.

Now my question is, how can I catch the last inner exception when using the -ErrorAction Stop flag. Should I just throw a PingException ? It doesn't seems to be a good idea since I can't be sure a PinException really is the cause of the ErrorAction trigger.

Upvotes: 1

Views: 718

Answers (1)

scharette
scharette

Reputation: 9997

Turns out that when using -ErrorAction Stop flag, non-terminating errors are wrapped and thrown as type System.Management.Automation.ActionPreferenceStopException. Therefore a solution would be to walk through the exception tree like so,

Try{
    $connection = Test-Connection -BufferSize 32 -Count 1 -ErrorAction Stop -ComputerName "test"
    return $connection.StatusCode.ToString()
}
Catch [System.Management.Automation.ActionPreferenceStopException]{
    $exception = $_.Exception
    #Walk through Exception tree
    while ($exception.InnerException) {
      $exception  = $exception.InnerException
    }
    #Return only the last inner exception
    return $exception.Message
}
Catch [Exception]{
    return "Unexpected exception"
}

EDIT

Note that my code is returning the last inner exception Message as a string. The same logic can be used to find other information if needed.

Upvotes: 2

Related Questions