Error Handling in modules

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Stephen Yeadon Stephen Yeadon 1 year, 5 months ago.

  • Author
    Posts
  • #28371
    Profile photo of Stephen Yeadon
    Stephen Yeadon
    Participant

    I have a powershell module to help with error handling. When i call methods in the error handling module from other modules the global $error variable appears empty even when it is not. I thought the $error variable was global and as such i would be able to do some thing like the following.

    In the below code the method Do-Something in the module 'Some other module' throws an exception or non terminating error which it elevates to a terminating exception. I would assume that the Display-Errors method that is called would be able to see the errors in the $error variable but it can not.

    # call do-something
    Do-Something
    
    
    # Module - Some other module *********************
    function Do-Something
    {
        Begin
        {
            # make all errors rterminating
            $ErrorActionPreference = 'Stop'
        }
        Process
        {
            if ($pscmdlet.ShouldProcess("Target", "Operation"))
            {
                try{
                    throw 'boom'
                    #blah blah blah
                }
                catch
                {
                    Display-Errors
                }
            }
        }
        End
        {
        }
    }
    # End of Module - Some other module *************
    
    
    
    # Module - Error handling ***************************
    function Display-Errors
    {    
        Write-Host( $Error | Format-List -Force | Out-String) -ForegroundColor Red -BackgroundColor Black 
    }
    # End of Module - Error handling ******************
    
  • #28403
    Profile photo of Don Jones
    Don Jones
    Keymaster

    $error is like any other variable – it's scoped. So if it gets changed in a module, that is only visible in the module. The best practice would be to capture that in the module in which it occurs, and pass it as a parameter to your error-handling routine. Functions shouldn't rely on global variables as a data-passing mechanism anyway, as a general rule.

  • #28409
    Profile photo of Stephen Yeadon
    Stephen Yeadon
    Participant

    Thanks for your help Don. That is what I have done. In general I don't rely on global scope as a mechanism for passing data about but I assumed that a parameter of global scope would behave more like a static property in C# and be available to and synchronized between all calling code.

    Thanks once again though.

You must be logged in to reply to this topic.