Wrie-Error doesn't work inside of Class method

This topic contains 1 reply, has 2 voices, and was last updated by  Patrick Meinecke 3 weeks, 1 day ago.

  • Author
    Posts
  • #83204

    Andy Mishechkin
    Participant

    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 ?

  • #83207

    Patrick Meinecke
    Participant

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

You must be logged in to reply to this topic.