我正在使用httparty创建本地gem,以连接到特定网站以获取身份验证 token 。输入正确的电子邮件和密码后,我可以使程序获取auth_token。但是,如果我输入了错误的电子邮件/密码,它将返回:NameError: uninitialized constant Gemname::InvalidStudentCodeError
require 'httparty'
class Gemname
include HTTParty
def initialize(email, password)
response = self.class.post("https://www.website.io/api/v1/sessions", body: {"email": email, "password": password})
#####error-handler#####
if StandardError
puts "invalid email/pass"
end
#######################
@auth_token = response["auth_token"]
end
end
似乎大多数错误都归类为standard error。
这个想法是从irb
Gemname.new('email', 'wrong-password')
运行,它将返回"Wrong email/password"
。如何处理错误以显示正确的消息?编辑:
我在初始化时尝试了以下代码:
if StandardError
"error"
end
我也试过
在lib文件夹上创建,该文件夹名为gemname-> error.rb
error.rb:
class InvalidStudentCodeError < StandardError
def initialize(msg="invalid email or password")
super(msg)
end
end
然后初始化:
raise InvalidStudentCodeError.new() if response.code == 401
最佳答案
下列升高方法解决了它:
def initialize(email, password)
response = self.class.post("https://www.website.io/api/v1/sessions", body: {"email": email, "password": password})
raise "invalid email/pass, bud" if response.code != 200
@auth_token = response["auth_token"]
end
关于ruby-on-rails - 使用httparty的用户名/密码错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276924/