I'd like to throw custom System.Management.Automation.ErrorRecord with some additional properties: ContextMessage and SqlCmdHeader.
I tried to create new class inherited from System.Management.Automation.ErrorRecord:
class SqlRequestException : System.Management.Automation.ErrorRecord
{
[hashtable]$SqlCmdHeader
[string]$ContextMessage
SqlRequestException() { }
SqlRequestException(
[string]$message,
[hashtable]$sqlCmdHeader,
[System.Management.Automation.ErrorRecord]$errorRecord
) : base($errorRecord, $null)
{
$this.SqlCmdHeader = $sqlCmdHeader
$this.ContextMessage = $message
}
}
But when I throw the error by this code:
try
{
#exceptions is risen here
}
catch
{
throw ([SqlRequestException]::New(
"Some context message of exception which will help to understand the error without additional debugging of code",
$sqlHeader,
$_))
}
I got in caller just System.Management.Automation.ErrorRecord without my awesome properties. Looks like throw cast my object to System.Management.Automation.ErrorRecord and lost the properties.
I'd like to ask you guys to help me to implement this logic in my script. Any help will be much appreciate!
Update
I'm not able to change caller's code. It always parses error and write it to logs:
try
{
# calling the method from module where I try to throw custom ErrorRecord
}
catch
{
Write-Log -Text $_
}
I cannot use System.Exception because when I throw created exception, all original information (such as InvocationInfo, ScriptStackTrace and etc) from ErrorRecord is lost. I couldn't find source code of throw statement to understand how exactly it works (maybe someone can point me to it?)
I see there is TargetObject property which could be used to store some additional information, but I don't see ways to put something to the property before throw statement since the property is ReadOnly and I think the property is not designed to store additional user's data.