Welcome Forums General PowerShell Q&A Error Handling in modules

Viewing 2 reply threads
  • Author
    Posts
    • #28371
      Participant
      Topics: 14
      Replies: 15
      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
      Topics: 18
      Replies: 4872
      Points: 1,902
      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
      Topics: 14
      Replies: 15
      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.

Viewing 2 reply threads
  • The topic ‘Error Handling in modules’ is closed to new replies.