2016-11-03 33 views
0

我正在使用Rails gem將請求發送到使用RestClient的api。我需要拯救401錯誤代碼。我看到RESTClient實現文檔如下:需要使用RestClient拯救401狀態代碼

> RestClient.get('http://my-rest-service.com/resource'){ |response, 
> request, result, &block| case response.code when 200 
>  p "It worked !" 
>  response when 423 
>  raise SomeCustomExceptionIfYouWant else 
>  response.return!(request, result, &block) end } 

我試圖執行一個類似的案例聲明:

case response.code 
when 200 
    JSON.parse(response.body) 
when 401 
    raise AuthenicationError, "Unauthorized" 
else 
    raise RestClient::ExceptionWithResponse 
end 

它抓住了200案件罰款,但忽視了401的情況下,並直去的人。對於通過RestClient返回的響應提出401異常的建議?

回答

2

我不能告訴你,爲什麼我確定剩下的客戶端回購可以告訴你:)但是使用RestClient::Request.new然後執行帶有塊的api調用適用於我。 我認爲這可能與RestClient內置異常事實有關。

request = RestClient::Request.new(
    method: :get, 
    url: 'https://my-rest-service.com/resource.json') 
response = request.execute {|response| $results = response} 
case response.code 
    when 200 
    puts "Good" 
    when 401 
    puts "Bad" 
    raise Exception 
end 
0

您正在使用錯誤的HTTP代碼。未經授權實際上是401,而不是410.

+0

對,抱歉,我仔細檢查了我的代碼,它實際上是在案件401剛當你輸入這個問題時,你會記得410。 – Bruce1138

+0

你確定響應的代碼實際上是401嗎?在case語句前添加'puts response.code'。 –

2

它抓住了200案件罰款,但忽略了401案件直去的人。

我寧可懷疑它不是轉到別人,其實;即使你完全剔除了else子句,你仍然會得到一個RestClient::ExceptionWithResponse,因爲that's what RestClient.getdoes when it gets an error response such as in the 400 or 500 range。從自述:

  • 爲200和207之間的結果代碼,一個RESTClient實現::響應將被返回
  • 爲結果代碼301,302或307,重定向將被如果請求是一個接着GET或HEAD
  • 對於結果代碼303,將遵循重定向,並且對於其他情況將請求轉換成GET請求,則會引發一個持有Response的RestClient :: ExceptionWithResponse;一個特定的異常類將拋出已知錯誤代碼
  • 調用.response除外上獲得服務器的響應