PowerShell error handling with functions

This is a matter of best practice, I suppose.

When designing functions to be used in scripts, what is the best way to handle errors that may occur inside a function?

For example, let's say we have a main function that does X and Y:

Function Test-Function { Try { <# Something in here that would generate an error #> } Catch { Throw } Return $someReturnResultIWantInMyScript } 

My script calls this function:

 Try { $ValueIWantFromFunction = Test-Function } Catch { <# Do something here #> } 

If Test-Function reaches a final error, it will call the caller. Try/Catch catch around my function call in the script will get this error and hit its own catch. Then I can decide what to do.

If I did not select the error inside the function, the script will not see the final error, and then my $ValueIWantFromFunction may contain $Null or something not useful.

Is this a good way to handle errors with functions and function calls inside scripts? Is there a better way?

+5
source share
1 answer

As a best practice, I like to use exceptions to handle errors in my functions / scripts and document them so that the caller knows what went wrong. For instance:

 Function Remove-File { [CmdletBinding()] [OutputType([Int])] Param( [Parameter(Mandatory)] [String]$Path ) Try { Remove-Item -Path $Path Return 0 } Catch { Return 1 } } 

If I create my own function / cmdlet, I will create a custom [ErrorRecord] object to throw:

 #Requires -Version 5 If ($ErrorCondition) { $PSCmdlet.ThrowTerminatingError( [System.Management.Automation.ErrorRecord]::new( [System.Exception]::new('Error message'), 'FullyQualifiedName', [System.Management.Automation.ErrorCategory]::DeviceError, $ErrorCausingObject ) ) } 

Using this method, I can include in the documentation which errors will be thrown depending on what went wrong so that the caller could use several catches depending on the error that occurred and process it.

Here are some good articles:
All About Exceptions
Scripting Guy: error handling
In attribute OutputType

0
source

Source: https://habr.com/ru/post/1273653/


All Articles