Error Handling #180
-
After much research and scripting I still find error handling in powershell difficult. I want to choose a standard way of throwing a terminating error. What would be the recommended way of doing this in a function and main script? There's so many options to choose from: Throw |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
How i have been handling errors at work ... $ErrorDetails = @{ Write-Error @ErrorDetails |
Beta Was this translation helpful? Give feedback.
-
Three things to consider: If the error is not always terminatingThen you should either To decide which to use, consider: If you want the user to debug where the error comes fromThen you can use Otherwise ...If the error is due to how the command was called, or put another way: if the error is expected and can be fixed outside your command, then you probably want to hide where (in your command) the error came from, so the error appears to come "from" the call to your command. In that case, you want to use |
Beta Was this translation helpful? Give feedback.
Three things to consider:
If the error is not always terminating
Then you should either
Write-Error
or$PSCmdlet.WriteError
and leave it up to the user to set-ErrorAction Stop
when they call your function.To decide which to use, consider:
If you want the user to debug where the error comes from
Then you can use
Write-Error -ErrorAction Stop
orthrow
because the error will come from where it is thrown from.Otherwise ...
If the error is due to how the command was called, or put another way: if the error is expected and can be fixed outside your command, then you probably want to hide where (in your command) the error came from, so the error appears to come "from" the call to your command.
…