Mock Invoke-WebRequest to throw an ErrorRecord

824 views
Skip to first unread message

craig buchanan

unread,
Mar 9, 2018, 5:21:03 PM3/9/18
to Pester
I'm using PowerShell to call a Twilio REST API method that will return an error as a JSON string.  For example:

{"code": 21602, "message": "Message body is required.", "more_info": "https://www.twilio.com/docs/errors/21602", "status": 400}

I would like to mock the Invoke-WebRequest cmdlet to throw an ErrorRecord that contains the minimal so that I can test my try/catch logic.

This approach:

Mock Invoke-WebRequest {

$errorRecord = New-Object System.Object.ErrorRecord
$errorRecord.Exception.Response.StatusCode = [System.Net.HttpStatusCode]::BadRequest
$errorRecord.ErrorDetails.Message = '{"code": 21602, "message": "Message body is required.", "more_info": "https://www.twilio.com/docs/errors/21602", "status": 400}'

Throw $errorRecord

}

Generates an error when the test is run:

Cannot find type [System.Object.ErrorRecord]: verify that the assembly containing this type is loaded.


Is there a better way to do this?

craig buchanan

unread,
Mar 19, 2018, 6:09:34 PM3/19/18
to Pester
The correct syntax is:

Mock Invoke-WebRequest {
$errorDetails = '{"code": 21212, "message": "The ''From'' number is not a valid phone number, shortcode, or alphanumeric sender ID.", "more_info": "https://www.twilio.com/docs/errors/21212", "status": 400}'
$statusCode = 400
$response = New-Object System.Net.Http.HttpResponseMessage $statusCode
$exception = New-Object Microsoft.PowerShell.Commands.HttpResponseException "$statusCode ($($response.ReasonPhrase))", $response
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation
$errorID = 'WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand'
$targetObject = $null
$errorRecord = New-Object Management.Automation.ErrorRecord $exception, $errorID, $errorCategory, $targetObject
$errorRecord.ErrorDetails = $errorDetails

Throw $errorRecord
}

Gianluca Salvo

unread,
Oct 19, 2018, 8:11:47 AM10/19/18
to Pester
Hi,
this snippet works very well. May you help me with the same but for the powershell Desktop (5.1)?

Thanks
Reply all
Reply to author
Forward
0 new messages