Как отличить исключение Invoke-WebRequest (код ошибки HTTP) в операторе try catch

Я создал сценарий для загрузки определенных файлов из Интернета с помощью сценария PowerShell с помощью командлета Invoke-WebRequest.

У меня есть 2 известных исключения, которые я хотел бы обработать: 404 и 429.

В настоящее время я работаю с оператором try/catch:

try {
    Invoke-WebRequest -Uri $download_url -OutFile $srr_file
} catch {
    ...snip...
}

Но для обеих ошибок у меня один и тот же код, и это не то, что я хотел бы сделать:

try {
    Invoke-WebRequest -Uri $download_url -OutFile $srr_file
} catch [something here] {
    # Here the code I would like to write if the HTTP response is 404 File not found
    # Will certainly be a continue command
} catch [something here] {
    # Here the code I would like to write if the HTTP response is 429 Too many request
    # Will certainly be a sleep command for 1 hour
}

Вот вывод команды в обеих ситуациях:

Error HTTP 404
Invoke-WebRequest : The remote server returned an error : (404) Not Found.
At line:1 char:1
+ Invoke-WebRequest -Uri https://<censored> -Outfile test.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Error HTTP 429
Invoke-WebRequest : The remote server returned an error : (429) Too Many Requests.
At line:1 char:1
+ Invoke-WebRequest -Uri "https://<censored> -Outfile test.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

person locobastos    schedule 09.10.2019    source источник


Ответы (1)


Вы можете сделать что-то вроде этого:

try 
{
    $response = Invoke-WebRequest -Uri $download_url -OutFile $srr_file
} 
catch 
{
    switch ($_.Exception.Response.StatusCode.Value__)
    {
        404 { 
            // Here´s the code I would like to write if the HTTP response is 404 File not found
            // Will certainly be a continue command            
            }
        429 {
            // Here´s the code I would like to write if the HTTP response is 429 Too many request
            // Will certainly be a sleep command for 1 hour 
            }
    }
}

Поскольку это одно и то же исключение, вы не сможете поймать их по отдельности.

person Palle Due    schedule 09.10.2019