2017-04-06 31 views
0

工作,我具備的功能GET_USER,搜索鍵入的用戶名:的try/catch不是在PowerShell中

function get_user 
{ 
    $url2 = "myurl/userName:" + $userName 

    $contentType2 = "application/json" 
    $basicAuth2 = post_token 
    $headers2 = @{ 
       Authorization = $basicAuth2 
      } 
    $body2 = @{ 
       grant_type = 'client_credentials' 
      } 
    $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2 -Headers $headers2 -Body $body2 

    return $getUser.userName 
} 

然後,我有我的主要方法try/catch語句這是不工作:

#MAIN 

try { 

$userName = Read-Host -Prompt "Input the user's username" 
$getUser = get_user 

    if ($userName -eq $getUser) 
     { 
      $courseId = Read-Host -Prompt "Input the course's ID" 
      $availability = Read-Host -Prompt "Available? (Yes/No)" 
      $courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)" 

      $confirmationEnrollment = putStudentCourse 
      " " 
      "####################################################" 
      "Success!" 
      "####################################################" 
     }  
    else 
     { 
      $firstName = Read-Host -Prompt "First Name" 
      $lastName = Read-Host -Prompt "Last Name" 
      $netId = $userName 
      $email = $userName + "@school.edu" 
      $password = Read-Host -Prompt "Password" 
      $uin = Read-Host -Prompt "ID Number" 
      $isAvailable = Read-Host -Prompt "Available? (Yes/No)" 

      $confirmationUserCreate = user_create 
      " " 
      "####################################################" 
      "User created!" 
      "####################################################" 
      " " 
      $courseId = Read-Host -Prompt "Input the course's ID" 

      $confirmEnroll = putStudentCourse 
      " " 
      "####################################################" 
      "User enrolled!" 
      "####################################################" 
     } 
    } 
catch [System.Net.HttpWebRequest] 
    { 
     "####################################################" 
     "User not found. We'll create it now!" 
     "####################################################" 
     " " 
    } 

現在你鍵入一個不存在的用戶名後拋出錯誤:

Invoke-RestMethod : The remote server returned an error: (404) Not Found. 
At E:\Blackboard_REST_API_Project\PowerShell\Post_Student_Course.ps1:42 char:13 
+  $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2 ... 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException 
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand 

我想隱藏紅色錯誤並輸出我在catch語句中的內容,但它跳過catch並直接跳到else找不到用戶名。有任何想法嗎?

+0

嗨emanresu。捕捉錯誤並輸出catch語句中的內容,太棒了!唯一的問題是它會終止程序並且它不會轉到else語句 – SPedraza

+0

您可能正在捕捉錯誤的異常類型。除此之外,我不認爲這個代碼會做你想做的。如果get_user引發錯誤,那麼您將跳過包含「用戶創建的」文本的代碼段。您是否意味着在發生錯誤時創建用戶? – emanresu

+0

正確。如果找到用戶,請繼續使用if語句(要求提供課程ID,它將註冊用戶,我有另一個功能)。如果沒有,跳轉到else語句並創建用戶。 – SPedraza

回答

0

關於Try Catch最可能的原因是發生了Catch之後明確列出的錯誤以外的錯誤。測試這種方法是刪除指定的異常類型,並捕獲所有錯誤。我不建議在生產代碼中這樣做,但爲了測試它至少會揭示您的總體想法是否正確。然後,您可以澄清要捕捉的具體錯誤。

對於理想的行爲似乎存在一些混淆。基於問題下面的評論和你的代碼評論,你似乎在說如果請求拋出一個錯誤,那麼用戶一定不存在,應該創建。如果這是正確的,那麼要小心,因爲這種假設並不總是如此。

一旦錯誤被拋出,你實際上會跳過你的If Else結構中的所有代碼。基本上我認爲你想在你的ELSE語句中使用邏輯並將其移入Catch塊。如果你想嘗試創建用戶,或者如果get_user拋出一個錯誤,或者如果它不拋出一個錯誤,但If條件失敗,那麼你會想要在catch和else中的相​​同邏輯。當然,創建一個函數可以更好地調用而不是重複代碼。

本質:

Try{ 
    #try to invoke the request 

    #if the request did not fail then compare the user entered text to the text returned from the request 
    #if these match then user already exists 
    #else the user does not exist so create it here 
} 
catch{ 
    #if the request failed assume that the user does not exist and create it here 

} 
+0

謝謝emanresu。這是一個語法問題。我從catch語句中刪除了錯誤類型,並將其他語句移到了catch語句中,它非常棒! – SPedraza

2

你檢查錯誤的異常類型的catch語句來。一個404引發錯誤的WebException

$Error[0] 
Invoke-RestMethod : The remote server returned an error: (404) Not Found. 
At line:2 char:5 
+  Invoke-RestMethod -Uri "http://www.vg.no/nonexistingpage" 
+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException 
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand 

$Error[0].Exception 

The remote server returned an error: (404) Not Found. 

$Error[0].Exception.GetType().FullName 

System.Net.WebException 

嘗試:

try { 
    Invoke-RestMethod -Uri "http://www.vg.no/nonexistingpage" 
} 
catch [System.Net.WebException] 
{ 
    "Exception caught!" 
} 

至於劇本,我可能會做這樣的事情,使創建用戶,如果它不(404-錯誤):

#MAIN 

$userName = Read-Host -Prompt "Input the user's username" 

try { 
    $getUser = get_user 
} catch [System.Net.WebException] { 
    #User doesn't exist, create new 
    $firstName = Read-Host -Prompt "First Name" 
    $lastName = Read-Host -Prompt "Last Name" 
    $netId = $userName 
    $email = $userName + "@school.edu" 
    $password = Read-Host -Prompt "Password" 
    $uin = Read-Host -Prompt "ID Number" 
    #Is it required to create user? If not, remove as it's specified later 
    $isAvailable = Read-Host -Prompt "Available? (Yes/No)" 

    $confirmationUserCreate = user_create 
    " " 
    "####################################################" 
    "User created!" 
    "####################################################" 

    #Verify user was created 
    $getUser = get_user 
} 

#Not sure if test is still needed.. 
if($userName -eq $getUser) { 
    $courseId = Read-Host -Prompt "Input the course's ID" 
    $availability = Read-Host -Prompt "Available? (Yes/No)" 
    $courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)" 

    $confirmationEnrollment = putStudentCourse 
    " " 
    "####################################################" 
    "Success!" 
    "####################################################" 
} 

提示:您應該在函數中使用參數,而不要依賴可能存在的變量。

+1

好主意,包括顯示如何獲取異常類型名稱的代碼片段。 – emanresu