Topic: how to return error_code and message_string from method?

Hi Guys,

I'm trying to write a ruby/rails API for a WebService (WSDL) but I'm stuck with the error handling. I know that in php i once used PEAR (new PEAR_error and and PEAR.is_error() ). I'm sure there is also a nice implementation for something like that in ruby.

so for example in my api class I have a method to login somewhere:

def start_session(username,password,ip=nil)
   if !@session.nil?
      # here I'd like to return an error code and an error string -> error object?
      return "session already in use"
   end
   response = @service.login(username,password,ip)
   if response.status_code == 0
      @session = response.message
   else
      # return another error object
      return "could not login to system"
   end       
   # everything is fine. we just return the session key
   return @session
  end

this method would then be called like that:

kt = myapi.new
@return_object = kt.start_session("user", "secret")
if !@return_object # check if something went wrong
   logger.error @return_object.message
else
   logger.info "session established"
end

how is that done proberly and "ruby" conform?
thanks for your help!
maze

Re: how to return error_code and message_string from method?

Errors really should't be just returned as strings. It should be raised and then you can rescue from it further up the stack. See this article for details.

Railscasts - Free Ruby on Rails Screencasts

Re: how to return error_code and message_string from method?

Ryan, thanks a lot! I changed my code as follows and it works nicely ;-)
cheers,
marcel

API:

  def start_session(username,password,ip=nil)
    raise "session in use"if !@session.nil?
    response = service.login(username,password,ip)
    if response.status_code == 0
      @session = response.message
    else
      @session = nil
      raise response.message
    end
    return response.status_code
  end

caller:
def login
    kt = Ktwsapi.new
    begin
      kt.start_session('user','secret')
    rescue Exception => boom
      @error = boom.message
    end
end

Last edited by maze (2007-06-02 13:44:51)