Error Handling in modules

Welcome Forums General PowerShell Q&A Error Handling in modules

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
3 years, 7 months ago.

  • Author
    Posts
  • #28371

    Participant
    Points: 21
    Rank: Member

    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

    Keymaster
    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    $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

    Participant
    Points: 21
    Rank: Member

    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.

The topic ‘Error Handling in modules’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort