How should a PowerShell module document its error behavior?

0
0
Asked By MellowCedar47 On

I maintain a PowerShell module with about 40 exported provisioning functions. I recently reviewed all 127 places where those functions report or handle errors: 52 used string-based throw, 34 used Write-Error followed by return, 23 used $PSCmdlet.ThrowTerminatingError with an ErrorRecord, 11 silently returned after a failed condition, and 7 threw constructed ErrorRecord objects.

The differences affected callers significantly. Write-Error produces a non-terminating error, while throw and ThrowTerminatingError can stop execution at different scopes. As a result, a caller using try/catch would only reliably catch some of the failures. I standardized the module so validation failures use ThrowTerminatingError, recoverable problems use the error stream, and silent returns now create proper error records. The module still has 127 error exits, but their behavior is now consistent and predictable.

What I still cannot find is a standard way to publish this contract. CmdletBinding, OutputType, and comment-based help do not appear to declare whether a function emits non-terminating errors, stops processing, or follows ErrorActionPreference. How do maintainers of public PowerShell modules document these distinctions for consumers?

3 Answers

Answered By QuartzHarbor8 On

There is no dedicated metadata attribute for this. You can document it in comment-based help, especially the .NOTES section, by explaining which conditions are terminating, which are non-terminating, and whether the function honors ErrorActionPreference. In practice, many modules leave callers to inspect the implementation or test the behavior, which is one of PowerShell's weaker areas.

Answered By NimbleOwl_62 On

For functions that support common cmdlet semantics, use the cmdlet APIs consistently: ThrowTerminatingError for failures that invalidate the whole operation, and $PSCmdlet.WriteError() for errors tied to an individual input object. Be careful with Write-Error followed by return, since it can make behavior and success-state handling less predictable. Document the intended behavior and test it with both the default error action and -ErrorAction Stop.

Answered By CopperVale19 On

A non-terminating error is often the right choice when processing pipeline input, because the command can report the bad object and continue with the rest. A terminating error makes more sense when the entire operation cannot proceed. Consumers can usually force non-terminating errors to stop with -ErrorAction Stop, but they cannot reliably make a function continue after it deliberately terminates, so honoring the standard error-action mechanism is important.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.