2017-04-22 49 views
0

我只是試圖尋找一個用戶時,如果用戶存在,甜的,如果沒有,我想聲明所以...爲什麼Spotify響應不允許我在收到錯誤時過去?

# Install if you haven't already 
require 'twilio-ruby' 
require 'rspotify' 

# Twilio Security Access 
account_sid = 'enter_your_sid' 
auth_token = 'enter_your_auth_token' 

# Spotify User Lookup 
def user_lookup(user_search) 
    spotify_user = RSpotify::User.find(user_search) 
end 

# Crafted text message using Twilio 
def text(account_sid, auth_token, message) 
    client = Twilio::REST::Client.new account_sid, auth_token 

    client.messages.create(
     from: '+twilio_number', # I guess you can use my number for testing 
     to: '+personal_number', # Feel free to enter your number to get the messages 
     body: message 
    ) 
end 

# Ask who you should lookup on Spotify 
puts "Who would you like to look up? " 
user_input_1 = gets.chomp 

# Make sure the user exists 
if user_lookup(user_input_1).id != user_input_1 # Test with "zxz122" 
    msg = "Could not find that Spotify user!" 
    text(account_sid, auth_token, msg) 
    puts "Spotify user details send failure!" 
else 
    user_exist = user_lookup(user_input_1) 
    user_profile_url = "https://open.spotify.com/user/#{user_input_1}" 
    msg = "Check out #{user_input_1} on Spotify: #{user_profile_url}" 
    text(account_sid, auth_token, msg) 
    puts "Spotify user details have been sent!" 
end 

我不斷收到的響應...

`return!': 404 Resource Not Found (RestClient::ResourceNotFound) 

那麼爲什麼它沒有擊中我的if語句並觸發「找不到Spotify用戶!」?

+0

看看如何處理'在他們的[自述] RESTClient實現的errors' (https://github.com/rest-client/rest-client#response-callbacks-error-handling) – DiodonHystrix

+0

是的 - 我花了幾個小時這樣做,雖然我似乎接近一些,但沒有結束了工作:( – code4fun

回答

0

爲什麼? RestClient的創建者設計了gem在資源不存在的情況下引發異常(aka返回404 not found)。

要解決此問題只是改變方法:

def user_lookup(user_search) 
    RSpotify::User.find(user_search) rescue false 
end 

,改變你的if ... else塊:

if user_lookup(user_input_1) 
    user_profile_url = "https://open.spotify.com/user/#{user_input_1}" 
    msg = "Check out #{user_input_1} on Spotify: #{user_profile_url}" 
    text(account_sid, auth_token, msg) 
    puts "Spotify user details have been sent!" 
else 
    msg = "Could not find that Spotify user!" 
    text(account_sid, auth_token, msg) 
    puts "Spotify user details send failure!" 
end 
+0

好吧 - 我試着添加「救助虛假」,現在t他發生了:'spotify_user_lookup.rb:37:'

':未定義的方法'id'爲false:FalseClass(NoMethodError)' – code4fun

+0

Nevermind!我改變我的if條件爲'user_lookup(user_input_1)== false',這似乎是在做伎倆。感謝您的幫助!! – code4fun

+0

我更新瞭解決該問題的答案。 – spickermann

相關問題