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