【问题标题】:Why won't the Spotify response allow me to go past when an error is received?为什么当收到错误时 Spotify 响应不允许我过去?
【发布时间】:2017-04-22 19:13:05
【问题描述】:

我只是想查找一个用户,如果该用户存在,很好,如果不存在,我想说明......

# 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 用户!”??

【问题讨论】:

  • 看看他们的readme如何处理RestClient's errors
  • 是的 - 我花了几个小时做这件事,虽然我似乎接近了一些,但最终都没有成功:(

标签: ruby api http error-handling spotify


【解决方案1】:

为什么? RestClient 的创建者设计 gem 以在资源不存在时引发异常(也就是返回 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

【讨论】:

  • 好的 - 我尝试添加“rescue false”,现在发生了这种情况:spotify_user_lookup.rb:37:in
    ': undefined method id' for false:FalseClass (NoMethodError)
  • 没关系!我将 if 条件更改为 user_lookup(user_input_1) == false,这似乎可以解决问题。谢谢你的帮助!!
  • 谢谢!它不会让我投票,因为我猜我还没有足够的声誉。不过我给了它复选标记!
猜你喜欢
  • 2016-07-21
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多