Quantcast
Channel: PowerShell General
Viewing all articles
Browse latest Browse all 10624

handling errors a level deeper

$
0
0

Hello,

is there easier way to distinguish between exceptions that are passed in another exceptions? How do you Experts handle this?

Acording to the option used in my example below a MethodInvocationException is raised. That exception does provide a message of the underlying exception, but no error code or something similar that provides information about the innerexception. I do not want to match the error action to the exception message raised.  (Matching message string is often advised but it can be presented in another language according to the system settings hence breaking my script.)

And I still want to be able to handle the general errors raised in the script block.

What I want to accomplish is a bullet proof scripting that is informative for the user in case of error and does not prevent me from debuging  :)

Btw: I know there are AD commandlets, adsi is used for example.

 

cls

 

try

{

#examples - uncomment only one option

#not existing station specified

#[adsi]::Exists("WinNT://notexisting/Administrators,Group")

 

#wrong syntax of the string - handle the inner exception

#[adsi]::Exists("WinNT:/\localhost/Administrators,Group")

 

#wrong syntax of function - handle the normal exception

#[adsi]::Ex("WinNT://localhost/Administrators,Group")

 

#this should run without any error

#[adsi]::Exists("WinNT://localhost/Administrators,Group")

 

 

}

catch [System.Management.Automation.MethodInvocationException]

{

#handle only the errors that are of the MethodInvocationExceptionType

switch ($error[0].exception.innerexception.ErrorCode)

{

-2147024843 {write-output ('The path was not found. You did not provide a correct computer name, or the workstation is not online.')}

#other error code options should be specified here

default {write-output ('Unknown error related to ADSI object.: ' + $error[0].exception.innerexception.message)}

}

}

catch

{

#handle all other errors

"unhandled error"

}

 


Viewing all articles
Browse latest Browse all 10624

Trending Articles