1
votes

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?

2
It's not quite clear what you're expecting. Where these exceptions should be handled? - montonero
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

2 Answers

1
votes

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
votes

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.