When I try to call one method from another method of Class with error handling, I can’t get the error message.
If I change Write-Error to Write-Host - all works fine, and method shows the error message.
What’s the right way of using of Write-Error in Class Methods ?
There isn’t one really. Methods aren’t meant to write non-terminating errors, it should fail or succeed. In other words you should use throw instead.
If you really need to write non-terminating errors, you need to pass in an instance of something with a command runtime like the $PSCmdlet variable from an advanced function.
using namespace System.Management.Automation
function Test-Function {
[CmdletBinding()]
param()
end {
[ErrorHandler]::WriteMyError($PSCmdlet)
}
}
class ErrorHandler {
static [void] WriteMyError([PSCmdlet] $ErrorContext) {
$ErrorContext.WriteError(
[ErrorRecord]::new(
[Exception]::new('My error message!'),
'MyErrorId',
[ErrorCategory]::InvalidOperation,
'MyTargetObject'))
}
}