使用httparty错误的用户名/密码错误处理

时间:2016-07-08 23:57:41

标签: ruby-on-rails api error-handling httparty

我正在使用httparty创建一个本地gem,以连接到特定网站以获取身份验证令牌。当我输入正确的电子邮件和密码时,我能够获取程序来获取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

1 个答案:

答案 0 :(得分:0)

以下提升方法解决了它:

 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