Vivere
Vivere

Reputation: 2280

How to properly write a C# error to powershell

Let's say I have the following block:

protected override void ProcessRecord()
{
  try
  {
    // code that throws
  }
  catch (System.Exception exception)
  {
    // handle error
  }
}

How can I properly write the exception? Using WriteError? Is the following a good approach?

WriteError(new ErrorRecord(exception, exception.Source, ErrorCategory.InvalidOperation, exception));

If so, should I be using ErrorRecord?

Upvotes: 1

Views: 634

Answers (1)

mklement0
mklement0

Reputation: 438083

Yes, you need an System.Management.Automation.ErrorRecord instance to report an error from a PowerShell cmdlet.

What method you use to report the error depends on whether you want it to be a terminating or, more typically, a non-terminating error:

See this answer for guidance on when to report which type of error.


As for what you tried:

WriteError(
  new ErrorRecord(
   exception,                      // parameter: exception
   exception.Source,               // errorId
   ErrorCategory.InvalidOperation, // category
   exception)                      // targetObject
);
  • You're passing the .Source property value of your exception to parameter errorId, but this parameter isn't meant to contain the originating application, but a (freely chosen) string identifying the type of error, such as PathNotFound, to which PowerShell automatically adds source information (the name of the originating command) and exposes it via the .FullyQualifiedErrorId property.

  • You're passing exception twice, but the last parameter, targetObject, isn't meant to refer to an exception, but to the object during whose processing the error occurred.

Upvotes: 3

Related Questions