Author Posts

October 29, 2017 at 6:21 am

Hello, All!
I try to execute the next code:

class Foo
{
    .....
    Static [int] method1()
    {
        $res = [Foo]::method2()
        ....
        return 0
    }
    Static [int] method2()
    {
        try
        { 
           ......
           return 0
        }
        catch 
        {
           Write-Error "Error: $_"
           return 1
        }
    }
}

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 ?

October 29, 2017 at 12:42 pm

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'))
    }
}