Skip to content

Instantly share code, notes, and snippets.

@ninmonkey
Last active September 29, 2022 20:20
Show Gist options
  • Save ninmonkey/7b98cc6761f986cf60dbe50869877511 to your computer and use it in GitHub Desktop.
Save ninmonkey/7b98cc6761f986cf60dbe50869877511 to your computer and use it in GitHub Desktop.
Handling Status Code Errors - Invoke-RestMethod.ps1
function processAPICall {
$irmSplat = @{
Uri = @(
$script:IrmConfig.BaseUrl
'/api/v2/companies/{0}/employees/{1}' -f @(
$companyId
$employeeId
)
) -join ''
Method = 'GET'
ResponseHeadersVariable = 'respHeaders'
StatusCodeVariable = 'statusCode'
SkipHttpErrorCheck = $true
# Credential = 'a'
# Token = 'x'
# SessionVariable = '_session'
RetryIntervalSec = 1
Headers = @{
# 'Authorization' = $script:IrmConfig.CurToken_BearerString
'Accept' = '*/*'
'Cache-Control' = 'no-cache'
'Host' = 'api.foo.com'
'Accept-Encoding' = 'gzip, deflate, br'
'Connection' = 'keep-alive'
}
}
$response = Invoke-RestMethod @irmSplat
$SharedCommonError -in @(401, 403, 429 ))
switch ($statusCode) {
200 {
return $response
}
{ $_ -in $sharedCommonError } {
$errStr = "HTTP Error Status: ${statusCode}, X = ${argX}, Y = ${argY}"
$errStr | Write-Error
$errStr | Write-Warning
}
401 {
GetNewAuth # or throw '401 ReAuth'
}
403 {}
429 {
Write-Error -ea 'continue' 'too many requests'
Start-Sleep -sec 10
}
default {
$errStr = "HTTP Error Status: ${statusCode}, X = ${argX}, Y = ${argY}"
throw $errStr
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment