tuggo
tuggo

Reputation: 23

Is there actually a best way to handle errors?

I am trying to provision a new stream analytics job using powershell script on azure, The following snippet is part of a script file which will add services to resource group.

sample code :

try{
    New-AzureRmStreamAnalyticsJob -ResourceGroupName $resourceGroup -File $template -Name $streamAnalyticsJobName -Force -ErrorAction Stop 
}catch{
    Write-Output $error[0] | Out-File -Append -FilePath $errLogFilePath

}

or

New-AzureRmStreamAnalyticsJob -ResourceGroupName $resourceGroup -File $template -Name $streamAnalyticsJobName -Force -ErrorVariable Errorvalue -ErrorAction SilentlyContinue
Write-Output Errorvalue | Out-File -Append -FilePath $errLogFilePath

what is recommended /best way to document errors in a log file for review.

Upvotes: 1

Views: 76

Answers (1)

mklement0
mklement0

Reputation: 437823

  • Your 1st command will also handle any terminating error issued by New-AzureRmStreamAnalyticsJob, thanks to use of try / catch.

    • Speaking generally, if the command had multiple inputs and issued non-terminating errors on a per-input basis - which means that processing would continue by default, even after a specific input causes a non-terminating error - your use of -ErrorAction Stop would actually short-circuit that and abort on encountering the first non-terminating error.
  • In your 2nd command, if a terminating error were to occur, your use of -ErrorAction SilentlyContinue would not be effective and neither would be your attempt to capture that error via -ErrorVariable - in short: common parameter -ErrorAction only affects non-terminating errors.

By contrast, the $ErrorActionPreference preference variable - surprisingly[1] - does also affect how terminating errors are treated, so, as a general pattern, you could to the following, if your intent is:

  • to continue processing, irrespective of whether errors occur and whether they are non-terminating or terminating.
  • to let errors occur silently, and only log them to a file.
  # Silently ignore any subsequent errors, irrespective of severity, but
  # still record them in the automatic $Error collection.
  $ErrorActionPreference = 'SilentlyContinue'

  # Save the current count of errors stored in $Error.
  $errCountBefore = $Error.Count

  New-AzureRmStreamAnalyticsJob -ResourceGroupName $resourceGroup -File $template -Name $streamAnalyticsJobName -Force

  # If errors occurred, append them to a log.
  if ($Error.Count -gt $errCountBefore) {
     $Error[$errCountBefore..($Error.Count-1)] >> $errLogFilePath
  } 

[1] For a comprehensive overview of PowerShell's error handling and its pitfalls, see this GitHub issue.

Upvotes: 2

Related Questions