← Docs home

Handle Errors Robustly

📐 Rule.

Cmdlets administer real systems, so they must report errors correctly. Distinguish terminating from non-terminating errors and route each through the right method.

Terminating error.

An error that stops the cmdlet from processing any more records. Call ThrowTerminatingError with an ErrorRecord. If an exception goes uncaught, the runtime throws a terminating error that carries less information.

Non-terminating error.

An error that does not stop processing of the next record from the pipeline. Call WriteError with an ErrorRecord. This lets the user perform the requested actions consistently and retain the information for the actions that fail. Handle each record as independently as possible. Example: one process fails to stop while others succeed.

The ErrorRecord exception.

An ErrorRecord requires an exception at its core. Follow the .NET design guidelines when choosing it. If the error is semantically the same as an existing exception, use or derive from that exception. Otherwise derive a new exception or hierarchy directly from System.Exception.

Error category.

An ErrorRecord also requires an error category that groups errors for the user. Categories come from the ErrorCategory enumeration. A user can view errors by category by setting $ErrorView to CategoryView.

Process-killing cases.

PowerShell does not catch these, and the process terminates.