One of the challenges of writing error handling is determining whether the error is terminating or non-terminating.
A possible solution is to force all errors to be terminating by setting ErrorActionPreference to Stop.
Setting ErrorActionPreference to Stop is equivalent to adding -ErrorAction Stop to every command that supports it.
When exploring nesting try-catch-finally, the following example was used:
try { Connect-Server Get-ManagementObject | ForEach-Object { try { $_ | Set-ManagementObject -Property 'NewValue' } catch { Write-Error -ErrorRecord $_ } finally { $_ } } } catch { throw
}
Setting ErrorActionPreference to Stop would remove the need to set an ErrorAction parameter on each of the commands (if those commands wrote non-terminating errors). However, doing so would also cause any informational errors written by Write-Error to completely stop the script.
For a script that implements a process, where the error handling can be strictly defined, the following workaround might be used. ErrorAction for Write-Error is forcefully set to Continue, overriding the value held in the preference variable:
$ErrorActionPreference = 'Stop' try { Connect-Server Get-ManagementObject | ForEach-Object { try { $_ | Set-ManagementObject -Property 'NewValue' } catch { Write-Error -ErrorRecord $_ -ErrorAction Continue } finally { $_ } } } catch { throw
}
Setting ErrorActionPreference to Stop is harder to apply when writing tools, such as when writing the commands used by this script; doing so would remove the choice from the end user.
A need for complex error handling is often a sign that a script should be broken down into smaller units.