I use to log the function name which has exception . The code is as below
function sample {
try{
$functionname = "sample"
throw "Error"
}
catch{
write-error "[$functionName] :Exception occured "
$_
}
}
sample
Now the same thing i am trying to follow in class method. But the variable declared in try block is not visible in catch block.
class sample{
[string] samplemethod() {
try{
$MethodName = "SampleMethod"
throw "error"
}
catch{
Write-error "[$MethodName] : Exception occured"
$_
}
return "err"
}
}
$obj = [sample]::new()
$obj.samplemethod()
It throws exception as below
At line:12 char:23 + Write-error "[$MethodName] : Exception occured" + ~~~~~~~~~~~ Variable is not assigned in the method.
Whether scope rule changed between class method and function?