1

I'm writing a PowerShell script with a try-catch that calls a bunch of functions.

function A {
  # exceptions here won't trigger the catch
}

function B {}

try {
  # exceptions here will trigger the catch

  A
  B
} catch {
  # handle errors
}

How do I get the functions to throw the exceptions upstream by default without writing a try catch block inside every functions?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sufendy
  • 1,212
  • 2
  • 16
  • 29
  • It's not quite clear what you're expecting. Where these exceptions should be handled? – montonero Mar 06 '19 at 07:27
  • Take a look at (https://stackoverflow.com/questions/15545429/erroractionpreference-and-erroraction-silentlycontinue-for-get-pssessionconfigur) – Paxz Mar 06 '19 at 08:14
  • Well, looks like it's working after all. I was having the problem where exceptions that happens inside a function doesn't trigger the catch block outside of it. But it's all good now. – Sufendy Mar 07 '19 at 00:32

2 Answers2

1

As per my understanding your are looking for capturing error of all the function without multiple try-catch. In this scenario you can use Error Logging mechanism to handle it

Error-logging Mechanism

function logger($val1 , $val2)
{
try
{
echo $val1 $val2
if ($val1 -eq 'Fail')
{ 
"Wrong Input passed so it was logged as error" + $val1 | out-file -Filepath $logfile -append
}
}
catch
{
$_.Exception.Message | out-file -Filepath $logfile -append
}
}
0

Not really clear what exceptions your trying to throw but if you just manually want to throw and error to stop the script use the throw command.

Hemme02
  • 34
  • 1
  • 7